Initial commit

This commit is contained in:
T 2018-01-03 14:43:54 +01:00
parent 7162a4909c
commit 638517981a
43 changed files with 1734 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target/
**/*.rs.bk
Cargo.lock

9
.idea/crossterm.iml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

9
.idea/misc.xml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CargoProjects">
<cargoProject FILE="$PROJECT_DIR$/Cargo.toml" />
</component>
<component name="RustProjectSettings">
<option name="toolchainHomeDirectory" value="$USER_HOME$/.cargo/bin" />
</component>
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/crossterm.iml" filepath="$PROJECT_DIR$/.idea/crossterm.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

293
.idea/workspace.xml Normal file
View File

@ -0,0 +1,293 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="310aeab2-4737-4e8e-b7eb-0aac10d104a3" name="Default" comment="" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="bin.rs" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/examples/bin.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="22" lean-forward="false" selection-start-line="0" selection-start-column="22" selection-end-line="0" selection-end-column="22" />
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="GradleLocalSettings">
<option name="externalProjectsViewState">
<projects_view />
</option>
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/examples/bin.rs" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="ProjectFrameBounds" extendedState="6">
<option name="x" value="2552" />
<option name="y" value="-8" />
<option name="width" value="1616" />
<option name="height" value="876" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
<manualOrder />
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scratches" />
<pane id="AndroidView" />
<pane id="PackagesPane" />
<pane id="Scope" />
<pane id="ProjectPane">
<subPane>
<expand>
<path>
<item name="crossterm" type="b2602c69:ProjectViewProjectNode" />
<item name="crossterm" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="crossterm" type="b2602c69:ProjectViewProjectNode" />
<item name="crossterm" type="462c0819:PsiDirectoryNode" />
<item name="examples" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="crossterm" type="b2602c69:ProjectViewProjectNode" />
<item name="crossterm" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
</pane>
</panes>
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="reference.settingsdialog.IDE.editor.colors.General" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="org.rust.cargo.project.model.PROJECT_DISCOVERY" value="true" />
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager">
<configuration default="true" type="Applet" factoryName="Applet">
<option name="HTML_USED" value="false" />
<option name="WIDTH" value="400" />
<option name="HEIGHT" value="300" />
<option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
<module />
</configuration>
<configuration default="true" type="Application" factoryName="Application">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="" />
<envs />
</configuration>
<configuration default="true" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="%MODULE_WORKING_DIR%" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
</configuration>
<configuration default="true" type="Remote" factoryName="Remote">
<option name="USE_SOCKET_TRANSPORT" value="true" />
<option name="SERVER_MODE" value="false" />
<option name="SHMEM_ADDRESS" value="javadebug" />
<option name="HOST" value="localhost" />
<option name="PORT" value="5005" />
</configuration>
<configuration default="true" type="TestNG" factoryName="TestNG">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="%MODULE_WORKING_DIR%" />
<option name="OUTPUT_DIRECTORY" />
<option name="ANNOTATION_TYPE" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<envs />
<properties />
<listeners />
</configuration>
<configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" factoryName="Plugin">
<module name="" />
<option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m -ea" />
<option name="PROGRAM_PARAMETERS" />
<predefined_log_file id="idea.log" enabled="true" />
</configuration>
</component>
<component name="ShelveChangesManager" show_recycled="false">
<option name="remove_strategy" value="false" />
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="310aeab2-4737-4e8e-b7eb-0aac10d104a3" name="Default" comment="" />
<created>1513618274599</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1513618274599</updated>
<workItem from="1513618275819" duration="650000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="650000" />
</component>
<component name="ToolWindowManager">
<frame x="2552" y="-8" width="1616" height="876" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Cargo" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Palette&#9;" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Image Layers" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Capture Analysis" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
<window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Capture Tool" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
<window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="UI Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Theme Preview" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
<watches-manager />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/examples/term_cursor_example/mod.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/examples/bin.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="22" lean-forward="false" selection-start-line="0" selection-start-column="22" selection-end-line="0" selection-end-column="22" />
<folding />
</state>
</provider>
</entry>
</component>
<component name="masterDetails">
<states>
<state key="ScopeChooserConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>

3
.vs/ProjectSettings.json Normal file
View File

@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

View File

@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}

BIN
.vs/crossterm/v15/.suo Normal file

Binary file not shown.

BIN
.vs/slnx.sqlite Normal file

Binary file not shown.

15
Cargo.toml Normal file
View File

@ -0,0 +1,15 @@
[package]
name = "crossterm"
version = "0.1.0"
authors = ["T <timonpost@hotmail.nl>"]
[dependencies]
[target.'cfg(target_os = "windows")'.dependencies]
winapi = "0.2.8"
kernel32-sys = "0.2.1"
[[bin]]
name="a"
path="examples\\bin.rs"

26
examples/bin.rs Normal file
View File

@ -0,0 +1,26 @@
extern crate crossterm;
use self::crossterm::terminal_style::{paint,Color};
use self::crossterm::terminal_cursor::cursor;
use std::io::Write;
fn main()
{
cursor::get().move_down(1);
print!("2");
std::io::stdout().flush().expect("asdf");
cursor::get().move_down(1);
print!("3");
std::io::stdout().flush().expect("asdf");
cursor::get().move_down(1);
print!("4");
std::io::stdout().flush().expect("asdf");
cursor::get().move_down(1);
print!("5");
std::io::stdout().flush().expect("asdf");
}

View File

@ -0,0 +1,8 @@
extern crate crossterm;
use self::crossterm::cursor;
pub fn goto(x: i16, y: i16)
{
cursor::get().goto(x,y);
}

4
src/kernel/mod.rs Normal file
View File

@ -0,0 +1,4 @@
#[cfg(windows)]
pub mod windows_kernel;
#[cfg(linux)]
pub mod linux_kernel;

View File

@ -0,0 +1,29 @@
extern crate kernel32;
extern crate winapi;
use self::winapi::HANDLE;
use super::handle;
/// Enables ansi for windows terminals.
pub fn enable_ansi_support() -> Result<(), u64>
{
const ENABLE_ANSI_CODES: u32 = 7;
let std_out_handle = handle::get_output_handle();
match std_out_handle
{
Some(handle) => { set_console_mode(handle, ENABLE_ANSI_CODES); Ok(()) },
None => return Err(0)
}
}
/// Set the console mode of the windows terminal.
fn set_console_mode(handle: HANDLE, enable_ansi_code: u32)
{
unsafe
{
kernel32::SetConsoleMode(handle, enable_ansi_code);
}
}

View File

@ -0,0 +1,138 @@
extern crate winapi;
extern crate kernel32;
use super::handle;
use super::kernel;
use terminal_style as style;
/// This will set the forground color by the given winapi color value parsed to u16.
pub fn set_fg_color(fg_color: u16)
{
if let Some(buffer_info) = kernel::get_console_screen_buffer_info()
{
// Notice that the color values are stored in wAttribute.
// So wee need to use bitwise operators to check if the values exists or to get current console colors.
let mut color: u16;
let attrs = buffer_info.wAttributes;
let bg_color = attrs & 0x0070;
color = fg_color | bg_color;
// background intensity is a seperate value in attrs,
// wee need to check if this was applied to the current bg color.
if (attrs & winapi::BACKGROUND_INTENSITY as u16) != 0
{
color = color | winapi::BACKGROUND_INTENSITY as u16;
}
set_console_text_attribute(color);
}
}
/// This will set the forground color by the given winapi color value parsed to u16.
pub fn set_bg_color(bg_color: u16)
{
if let Some(buffer_info) = kernel::get_console_screen_buffer_info()
{
// Notice that the color values are stored in wAttribute.
// So wee need to use bitwise operators to check if the values exists or to get current console colors.
let mut color: u16;
let attrs = buffer_info.wAttributes;
let fg_color = attrs & 0x0007;
color = fg_color | bg_color;
// foreground intensity is a seperate value in attrs,
// wee need to check if this was applied to the current fg color.
if (attrs & winapi::FOREGROUND_INTENSITY as u16) != 0
{
color = color | winapi::FOREGROUND_INTENSITY as u16;
}
set_console_text_attribute(color);
}
}
/// This will reset the colors to the value given in u16.
pub fn reset(original_color: u16)
{
set_console_text_attribute(original_color);
}
/// This will get the winapi color value from the Color struct
pub fn winapi_color_val(color: style::Color, color_type: style::ColorType) -> u16
{
use terminal_style::{ColorType, Color};
let winapi_color: u32;
let fg_green = winapi::FOREGROUND_GREEN;
let fg_red = winapi::FOREGROUND_RED;
let fg_blue = winapi::FOREGROUND_BLUE;
let fg_intensity = winapi::FOREGROUND_INTENSITY;
let bg_green = winapi::BACKGROUND_GREEN;
let bg_red = winapi::BACKGROUND_RED;
let bg_blue = winapi::BACKGROUND_BLUE;
let bg_intensity = winapi::BACKGROUND_INTENSITY;
match color_type
{
ColorType::Foreground =>
{
winapi_color = match color
{
Color::Black => 0,
Color::Red => fg_intensity | fg_red,
Color::DarkRed => fg_red,
Color::Green => fg_intensity | fg_green,
Color::DarkGreen => fg_green,
Color::Yellow => fg_intensity | fg_green | fg_red,
Color::DarkYellow => fg_green | fg_red,
Color::Blue => fg_intensity | fg_blue,
Color::DarkBlue => fg_blue,
Color::Magenta => fg_intensity | fg_red | fg_blue,
Color::DarkMagenta => fg_red | fg_blue,
Color::Cyan => fg_intensity | fg_green | fg_blue,
Color::DarkCyan => fg_green | fg_blue,
Color::Grey => fg_intensity,
Color::White => fg_intensity | fg_red | fg_green | fg_blue,
};
},
ColorType::Background =>
{
winapi_color = match color
{
Color::Black => 0,
Color::Red => bg_intensity | bg_red,
Color::DarkRed => bg_red,
Color::Green => bg_intensity | bg_green,
Color::DarkGreen => bg_green,
Color::Yellow => bg_intensity | bg_green | bg_red,
Color::DarkYellow => bg_green | bg_red,
Color::Blue => bg_intensity | bg_blue,
Color::DarkBlue => bg_blue,
Color::Magenta => bg_intensity | bg_red | bg_blue,
Color::DarkMagenta => bg_red | bg_blue,
Color::Cyan => bg_intensity | bg_green | bg_blue,
Color::DarkCyan => bg_green | bg_blue,
Color::Grey => bg_intensity,
Color::White => bg_intensity | bg_red | bg_green | bg_blue,
};
}
};
winapi_color as u16
}
/// This will set the console attributes by the given value
fn set_console_text_attribute(value: u16)
{
let output_handle = handle::get_output_handle();
if let Some(handle) = output_handle
{
unsafe
{
kernel32::SetConsoleTextAttribute(handle, value);
}
}
}

View File

@ -0,0 +1,93 @@
extern crate winapi;
extern crate kernel32;
use self::winapi::{COORD};
use super::{handle,kernel};
/// These are the movement directions of an cursor
#[derive(Debug)]
pub enum CursorDirection
{
Top,
Right,
Down,
Left,
}
/// Set the cursor position to an coordinate (x,y).
pub fn set(x: u16, y:u16)
{
set_cursor_pos(x as i16,y as i16);
}
/// Get the current cursor x position.
pub fn xpos() -> u16
{
if let Some(csbi) = kernel::get_console_screen_buffer_info()
{
csbi.dwCursorPosition.Y as u16
}else{
println!("xpos verkeerd");
0
}
}
/// Get the current cursor y position.
pub fn ypos() -> u16
{
if let Some(csbi) = kernel::get_console_screen_buffer_info()
{
csbi.dwCursorPosition.Y as u16
}else{
println!("ypos verkeerd");
0
}
}
pub fn move_down(count: u16)
{
if let Some(buffer) = kernel::get_console_screen_buffer_info()
{
unsafe
{
let handle = kernel32::GetStdHandle(winapi::STD_OUTPUT_HANDLE);
kernel32::SetConsoleCursorPosition(handle, COORD {
X: buffer.dwCursorPosition.X,
Y: buffer.dwCursorPosition.Y + count as i16,
});
}
}
}
// pub fn move_direction(count: i16, cursor_direction: CursorDirection)
// {
//
// println!("{}, {}, {:?}",x,y, cursor_direction);
// match cursor_direction
// {
// CursorDirection::Top => set_cursor_pos(x,y - count) ,
// CursorDirection::Right => set_cursor_pos(x + count, y) ,
// CursorDirection::Down => set_cursor_pos(x, y + count),
// CursorDirection::Left => set_cursor_pos(x - count,y),
// };
// }else{
// println!("{}", "Not found");
// }
// }
/// Set the cursor position to an coordinate (x,y).
fn set_cursor_pos(x: i16, y: i16)
{
if let Some(handle) = handle::get_output_handle()
{
unsafe
{
let position = COORD{X: x, Y:y};
kernel32::SetConsoleCursorPosition(handle, position);
}
}
}

View File

@ -0,0 +1,98 @@
extern crate winapi;
extern crate kernel32;
use std::os::windows::io::{AsRawHandle, RawHandle};
use self::winapi::{HANDLE, STD_OUTPUT_HANDLE, STD_INPUT_HANDLE};
use std::mem;
static mut CONSOLE_INPUT_HANDLE:Option<HANDLE> = None;
static mut CONSOLE_OUTPUT_HANDLE:Option<HANDLE> = None;
/// Get the std_output_handle of the console
pub fn get_output_handle() -> Option<HANDLE>
{
unsafe
{
// if let Some(handle) = CONSOLE_OUTPUT_HANDLE
// {
// match handle_check(&handle)
// {
// true => {
// CONSOLE_OUTPUT_HANDLE = Some(handle);
// CONSOLE_OUTPUT_HANDLE
// },
// false => None
// }
// } else {
let handle = kernel32::GetStdHandle(STD_OUTPUT_HANDLE);
match handle_check(&handle)
{
true => {
// CONSOLE_OUTPUT_HANDLE = Some(handle);
Some(handle)
},
false => None
}
}
// }
}
/// Get the std_input_handle of the console
pub fn get_input_handle() -> Option<HANDLE>
{
unsafe
{
if let Some(handle) = CONSOLE_INPUT_HANDLE
{
match handle_check(&handle)
{
true => {
CONSOLE_INPUT_HANDLE = Some(handle);
CONSOLE_INPUT_HANDLE
},
false => None
}
}
else
{
let handle = kernel32::GetStdHandle(STD_INPUT_HANDLE);
match handle_check(&handle)
{
true => {
CONSOLE_INPUT_HANDLE = Some(handle);
CONSOLE_INPUT_HANDLE
},
false => None
}
}
}
}
pub fn as_raw_handle() -> Option<(HANDLE, winapi::CONSOLE_SCREEN_BUFFER_INFO)>
{
unsafe
{
let hand = kernel32::GetStdHandle(STD_OUTPUT_HANDLE) as RawHandle;
let mut csbi: winapi::CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed() ;
match kernel32::GetConsoleScreenBufferInfo(hand, &mut csbi)
{
0 => None,
_ => Some((hand, csbi)),
}
}
}
/// Checks if the console handle is an invalid handle value.
fn handle_check(handle: &HANDLE) -> bool
{
if *handle == winapi::INVALID_HANDLE_VALUE
{
false
}else{
true
}
}

View File

@ -0,0 +1,43 @@
extern crate winapi;
extern crate kernel32;
use super::handle;
use self::winapi::CONSOLE_SCREEN_BUFFER_INFO;
use std::mem;
/// Get console screen buffer info.
pub fn get_console_screen_buffer_info() -> Option<CONSOLE_SCREEN_BUFFER_INFO>
{
let handle = handle::get_output_handle();
let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = unsafe { mem::zeroed() };
unsafe
{
if let Some(x) = handle
{
match kernel32::GetConsoleScreenBufferInfo(x, &mut csbi)
{
0 => None,
_ => Some(csbi),
}
}
else {
None
}
}
}
/// Get the current console colors.
pub fn get_original_console_color() -> u16
{
let console_buffer_info = get_console_screen_buffer_info();
if let Some(buffer_info) = console_buffer_info
{
buffer_info.wAttributes as u16
}
else{
300
}
}

View File

@ -0,0 +1,5 @@
pub mod cursor;
pub mod color;
pub mod ansi_support;
pub mod handle;
pub mod kernel;

13
src/lib.rs Normal file
View File

@ -0,0 +1,13 @@
#[macro_use]
pub mod shared;
pub mod terminal_cursor;
pub mod terminal_style;
mod kernel;
pub use shared::traits::Construct;
pub use terminal_cursor::cursor;
pub use terminal_style::paint;

56
src/shared/macros.rs Normal file
View File

@ -0,0 +1,56 @@
use std;
use std::fmt;
use std::io::Write;
use terminal_style as style;
/// This is used to make StyledObject able to be displayed.
/// This macro will set the styled stored in Styled Object
#[macro_export]
macro_rules! impl_fmt
{
($name:ident) => {
impl<D: fmt::$name> fmt::$name for style::StyledObject<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
let mut colored_terminal = style::colored_terminal();
let mut reset = true;
if let Some(bg) = self.object_style.bg_color
{
colored_terminal.set_bg(bg);
reset = true;
}
if let Some(fg) = self.object_style.fg_color
{
colored_terminal.set_fg(fg);
reset = true;
}
write!(f, "{}", &self.content);
std::io::stdout().flush().expect("Flush stdout failed");
if reset
{
colored_terminal.reset();
}
Ok(())
}
}
}
}
/// This macro will take an ANSI input and combines it with some default ANSI characters and returns the result
#[macro_export]
macro_rules! csi {
($( $l:expr ),*) => { concat!("\x1B[", $( $l ),*) };
}
/// This inplements Display for StyledObject
/// Notice that more implementations can be maked.
/// # Example
/// ```rust
/// example impl_fmt!(Debug);
/// ```
impl_fmt!(Display);

3
src/shared/mod.rs Normal file
View File

@ -0,0 +1,3 @@
#[macro_use]
pub mod macros;
pub mod traits;

6
src/shared/traits.rs Normal file
View File

@ -0,0 +1,6 @@
/// This trait is used for creating an instance of an concrete implementation from an base trait.
/// This trait allows the output to be different in size.
pub trait Construct
{
fn new() -> Box<Self> where Self: Sized;
}

View File

View File

View File

View File

@ -0,0 +1,41 @@
use Construct;
use super::base_cursor::ITerminalCursor;
/// This struct will be used for ansi terminals and unix systems.
pub struct AnsiCursor;
impl Construct for AnsiCursor
{
fn new() -> Box<AnsiCursor>
{
Box::from(AnsiCursor {})
}
}
impl ITerminalCursor for AnsiCursor
{
fn goto(&self, x: i16 , y: i16)
{
format!(csi!("{};{}H"), x,y);
}
fn move_up(&self,count: u16)
{
format!(csi!("{}A"), count);
}
fn move_right(&self, count: u16)
{
format!(csi!("{}C"), count);
}
fn move_down(&self, count: u16)
{
format!(csi!("{}B"), count);
}
fn move_left(&self, count: u16)
{
format!(csi!("{}D"), count);
}
}

View File

@ -0,0 +1,19 @@
/// This trait defines the actions that can be preformed on the termial cursor.
/// This trait can be inplemented so that an concrete inplementation of the ITerminalCursor can forfill
/// the wishes to work on an specific platform.
///
/// ## For example:
///
/// This trait is inplemented for winapi (Windows specific) and ansi (Unix specific),
/// so that the cursor related actions can be preformed on both unix and windows systems.
pub trait ITerminalCursor
{
/// Goto some location (x,y) in the terminal.
fn goto(&self, x: i16, y: i16);
fn move_up(&self, count: u16);
fn move_right(&self, count: u16);
fn move_down(&self, count: u16);
fn move_left(&self, count: u16);
}

View File

@ -0,0 +1,133 @@
use std::fmt::Display;
use std;
use std::io::Write;
use Construct;
use super::base_cursor::ITerminalCursor;
use super::{AnsiCursor, WinApiCursor, NoCursor};
/// Struct with the cursor on wits cursor realated actions can be performed.
pub struct TerminalCursor
{
terminal_cursor: Option<Box<ITerminalCursor>>,
}
impl TerminalCursor
{
/// Instantiate an cursor implementation whereon cursor related actions can be performed.
pub fn init(&mut self)
{
if let None = self.terminal_cursor
{
self.terminal_cursor = get_cursor_options();
}
}
/// Goto some location (x,y) in the terminal.
///
/// #Example
///
/// ```rust
/// extern crate crossterm;
///
/// use self::crossterm::terminal_cursor::{cursor,TerminalCursor};
/// fn main()
/// {
/// cursor::get().goto(10,10);
/// }
/// ```
pub fn goto(mut self, x: i16 , y: i16) -> TerminalCursor
{
&self.init();
if let Some(ref terminal_cursor) = self.terminal_cursor
{
terminal_cursor.goto(x,y);
}
self
}
/// Print an value at the current cursor location.
///
/// #Example
///
/// ```rust
/// extern crate crossterm;
///
/// use self::crossterm::terminal_cursor::{cursor,TerminalCursor};
/// fn main()
/// {
/// // of course we can just do this.
/// print!("@").
/// // but now we can chain the methods so it looks cleaner.
/// cursor::get()
/// .goto(10,10)
/// .print("@");
/// }
/// ```
pub fn move_up(mut self, count: u16) -> TerminalCursor
{
&self.init();
if let Some(ref terminal_cursor) = self.terminal_cursor
{
terminal_cursor.move_up(count);
}
self
}
pub fn move_right(mut self, count: u16) -> TerminalCursor
{
&self.init();
if let Some(ref terminal_cursor) = self.terminal_cursor
{
terminal_cursor.move_right(count);
}
self
}
pub fn move_down(mut self, count: u16) -> TerminalCursor
{
&self.init();
if let Some(ref terminal_cursor) = self.terminal_cursor
{
terminal_cursor.move_down(count);
}
self
}
pub fn move_left(mut self, count: u16) -> TerminalCursor
{
&self.init();
if let Some(ref terminal_cursor) = self.terminal_cursor
{
terminal_cursor.move_left(count);
}
self
}
pub fn print<D: Display>(self, value:D) -> TerminalCursor
{
print!("{}", value);
self
}
}
/// Get the concrete ITerminalCursor implementation based on the current operating system.
fn get_cursor_options() -> Option<Box<ITerminalCursor>>
{
if cfg!(target_os = "linux") {
Some(AnsiCursor::new())
}
else if cfg!(target_os = "windows") {
Some(WinApiCursor::new())
}else{
Some(NoCursor::new())
}
}
/// Get terminal cursor options whereon cursor related actions can be performed.
pub fn get() -> Box<TerminalCursor>
{
Box::from(TerminalCursor { terminal_cursor: get_cursor_options() })
}

View File

@ -0,0 +1,11 @@
mod base_cursor;
mod no_cursor;
mod ansi_cursor;
mod winapi_cursor;
pub mod cursor;
use self::no_cursor::NoCursor;
use self::ansi_cursor::AnsiCursor;
use self::winapi_cursor::WinApiCursor;
pub use cursor::{get, TerminalCursor};

View File

@ -0,0 +1,31 @@
use Construct;
use super::base_cursor::ITerminalCursor;
/// Struct that will be instantiated when something went wrong or when an platform does not suport
/// the current concrete cursor inplementations.
pub struct NoCursor;
impl Construct for NoCursor
{
fn new() -> Box<NoCursor> {
Box::new(NoCursor {})
}
}
impl ITerminalCursor for NoCursor
{
fn goto(&self, x: i16 , y: i16)
{ }
fn move_up(&self, count: u16)
{ }
fn move_right(&self, count: u16)
{ }
fn move_down(&self, count: u16)
{ }
fn move_left(&self, count: u16)
{ }
}

View File

@ -0,0 +1,57 @@
use Construct;
use kernel::windows_kernel::cursor;
use super::base_cursor::ITerminalCursor;
/// This struct will be used for cursor actions in windows terminals performed by winapi.
pub struct WinApiCursor
{
has_moved: bool,
}
impl Construct for WinApiCursor
{
fn new() -> Box<WinApiCursor>
{
Box::from(WinApiCursor {has_moved: false})
}
}
impl ITerminalCursor for WinApiCursor
{
fn goto(&self, x: i16 , y: i16)
{
// cursor::set(x,y);
}
fn move_up(&self, count: u16)
{
let xpos = cursor::xpos();
let ypos = cursor::ypos();
cursor::set(xpos, ypos -1);
}
fn move_right(&self, count: u16)
{
let xpos = cursor::xpos();
let ypos = cursor::ypos();
cursor::set(xpos + 1, ypos);
}
fn move_down(&self, count: u16)
{
let xpos = cursor::xpos();
let ypos = cursor::ypos();
cursor::set(xpos, ypos + count);
}
fn move_left(&self, count: u16)
{
let xpos = cursor::xpos();
let ypos = cursor::ypos();
cursor::set(xpos -1, ypos);
}
}

View File

@ -0,0 +1,87 @@
use std::string::String;
use Construct;
use super::color::{Color,ColorType};
use super::base_color::{ ITerminalColor, sum_u16_to_string };
/// This struct will be used for coloring ansi terminals with ansi escape codes.
#[derive(Debug)]
pub struct ANSIColor;
impl Construct for ANSIColor
{
fn new() -> Box<ANSIColor>
{
Box::from(ANSIColor {})
}
}
impl ITerminalColor for ANSIColor
{
fn set_fg(&self, fg_color: Color)
{
format!(csi!("38;2;{}m"), self.color_value(fg_color,ColorType::Foreground));
}
fn set_bg(&self, bg_color: Color)
{
format!(csi!("38;2;{}m"), self.color_value(bg_color,ColorType::Background));
}
fn reset(&self)
{
format!(csi!("0m"));
}
fn color_value(&self, color: Color, color_type: ColorType) -> String
{
let mut ansi_color_code = String::new();
// The ansi code for forground = 30 and background = 40;
match color_type
{
ColorType::Foreground => ansi_color_code.push_str("30"),
ColorType::Background => ansi_color_code.push_str("40"),
}
// Construct ANSI escape color code string. ;1 is for the brightness
match color
{
Color::Black => { sum_u16_to_string(0, &mut ansi_color_code); },
Color::Red => sum_u16_to_string(1, &mut ansi_color_code),
Color::DarkRed => {
sum_u16_to_string(1, &mut ansi_color_code);
&ansi_color_code.push_str(";1");
},
Color::Green => sum_u16_to_string(2, &mut ansi_color_code),
Color::DarkGreen => {
sum_u16_to_string(2, &mut ansi_color_code);
&ansi_color_code.push_str(";1");
},
Color::Yellow => sum_u16_to_string(3, &mut ansi_color_code),
Color::DarkYellow => {
sum_u16_to_string(3, &mut ansi_color_code);
&ansi_color_code.push_str(";1");
},
Color::Blue => sum_u16_to_string(4, &mut ansi_color_code),
Color::DarkBlue => {
sum_u16_to_string(4, &mut ansi_color_code);
&ansi_color_code.push_str(";1");
},
Color::Magenta => sum_u16_to_string(5, &mut ansi_color_code),
Color::DarkMagenta => {
sum_u16_to_string(5, &mut ansi_color_code);
&ansi_color_code.push_str(";1");
},
Color::Cyan => sum_u16_to_string(6, &mut ansi_color_code),
Color::DarkCyan =>
{
sum_u16_to_string(6, &mut ansi_color_code);
&ansi_color_code.push_str(";1");
},
Color::Grey => sum_u16_to_string(7, &mut ansi_color_code),
Color::White => sum_u16_to_string(7, &mut ansi_color_code),
}
ansi_color_code
}
}

View File

@ -0,0 +1,33 @@
/// This trait defines the actions that can be preformed on the termial color.
/// This trait can be inplemented so that an concrete inplementation of the ITerminalColor can forfill
/// the wishes to work on an specific platform.
///
/// ## For example:
///
/// This trait is inplemented for winapi (Windows specific) and ansi (Unix specific),
/// so that the color related actions can be preformed on both unix and windows systems.
use super::color::{Color,ColorType};
pub trait ITerminalColor
{
/// Set the forground color to the given color.
fn set_fg(&self, fg_color: Color);
/// Set the background color to the given color.
fn set_bg(&self, fg_color: Color);
/// Reset the terminal color to default.
fn reset(&self);
/// Gets an value that represents an color from the given `Color` and `ColorType`.
fn color_value(&self, color: Color, color_type: ColorType) -> String;
}
/// Sum an u16 value with an string (also a numeric value).
pub fn sum_u16_to_string(value: u16, string: &mut String)
{
let parsed_string: u16 = string.parse().unwrap();
let new_value: u16 = parsed_string + value;
*string = new_value.to_string();
}

View File

@ -0,0 +1,227 @@
use std::fmt;
use std::convert::From;
use std::str::FromStr;
use Construct;
use super::{WinApiColor, ANSIColor,NoTerminalColor};
use super::base_color::ITerminalColor;
use terminal_style::{ObjectStyle,StyledObject};
/// Colors that are available for coloring the termainal font.
#[derive(Debug)]
#[derive(Copy, Clone)]
pub enum Color
{
Black,
Red,
DarkRed,
Green,
DarkGreen,
Yellow,
DarkYellow,
Blue,
DarkBlue,
Magenta,
DarkMagenta,
Cyan,
DarkCyan,
Grey,
White,
}
/// Color types
#[derive(Debug)]
#[derive(Copy, Clone)]
pub enum ColorType
{
Background,
Foreground,
}
/// Enables an user to pass in an color as str.
/// *Default color if cannot be parsed will be white.*
///
/// # Example
///
/// ``` rust
/// let fg_color = Color::from("red");
/// let bg_color = Color::from("blue");
///
/// println!("{}",paint("■").with(fg_color).on(bg_color));
/// ```
impl<'a> From<&'a str> for Color {
fn from(src: &str) -> Self {
src.parse().unwrap_or(Color::White)
}
}
/// Enables an user to pass in an color as String.
/// *Default color if cannot be parsed will be white.*
///
/// # Example
///
/// ``` rust
/// let fg_color = Color::from(String::from("red"));
/// let bg_color = Color::from(String::from("blue"));
///
/// println!("{}",paint("■").with(fg_color).on(bg_color));
/// ```
impl From<String> for Color {
fn from(src: String) -> Self {
src.parse().unwrap_or(Color::White)
}
}
impl FromStr for Color {
type Err = ();
fn from_str(src: &str) -> Result<Self, Self::Err> {
let src = src.to_lowercase();
match src.as_ref() {
"black" => Ok(Color::Black),
"red" => Ok(Color::Red),
"dark_red" => Ok(Color::DarkRed),
"green" => Ok(Color::Green),
"dark_green" => Ok(Color::DarkGreen),
"yellow" => Ok(Color::Yellow),
"dark_yellow" => Ok(Color::DarkYellow),
"blue" => Ok(Color::Blue),
"dark_blue" => Ok(Color::DarkBlue),
"magenta" => Ok(Color::Magenta),
"dark_magenta" => Ok(Color::DarkMagenta),
"cyan" => Ok(Color::Cyan),
"dark_cyan" => Ok(Color::DarkCyan),
"grey" => Ok(Color::Grey),
"white" => Ok(Color::White),
_ => Ok(Color::White),
}
}
}
/// Struct on wits the color realated actions can be performed.
pub struct TerminalColor
{
terminal_color: Option<Box<ITerminalColor>>,
}
impl TerminalColor
{
/// Instantiate an color implementation whereon color related actions can be performed.
pub fn init(&mut self)
{
if let None = self.terminal_color
{
self.terminal_color = get_color_options();
}
}
/// Set the forground color to the given color.
///
/// #Example
///
/// ```rust
///
/// let mut colored_terminal = colored_terminal();
/// colored_terminal.set_fg(Color::Red);
///
/// ```
pub fn set_fg(&mut self, color: Color)
{
&self.init();
if let Some(ref terminal_color) = self.terminal_color
{
terminal_color.set_fg(color);
}
}
/// Set the background color to the given color.
///
/// #Example
///
/// ```rust
///
/// let mut colored_terminal = colored_terminal();
/// colored_terminal.set_bg(Color::Red);
///
/// ```
pub fn set_bg(&mut self, color: Color)
{
&self.init();
if let Some(ref terminal_color) = self.terminal_color
{
terminal_color.set_bg(color);
}
}
/// Reset the terminal colors to default.
/// # Example
///
/// ```rust
///
/// let mut colored_terminal = colored_terminal();
/// colored_terminal.reset();
///
/// ```
pub fn reset(&mut self)
{
&self.init();
if let Some(ref terminal_color) = self.terminal_color
{
terminal_color.reset();
}
}
}
/// Get the concrete ITerminalColor implementation based on the current operating system.
fn get_color_options() -> Option<Box<ITerminalColor>>
{
if cfg!(target_os = "linux") {
Some(ANSIColor::new())
}
else if cfg!(target_os = "windows") {
Some(WinApiColor::new())
}else{
Some(NoTerminalColor::new())
}
}
/// Get the terminal options for colors, whereon color related actions can be performed.
pub fn colored_terminal() -> Box<TerminalColor>
{
Box::from(TerminalColor { terminal_color: get_color_options() })
}
/// Wraps an displayable object so it can be formatted with colors and attributes.
///
/// #Example
///
/// ```rust
/// extern crate crossterm;
/// use self::crossterm::terminal_style::{paint,Color};
///
/// fn main()
/// {
/// // default foregroundcolor and backgroundcolor.
/// println!("{}",paint("■"));
///
/// // red foregroundcolor and Blue backgroundcolor
/// let styledobject = paint("■").with(Color::Red).on(Color::Blue);
/// println!("{}", styledobject);
/// }
/// ```
pub fn paint<D>(val: D) -> StyledObject<D> where D: fmt::Display
{
ObjectStyle::new().apply_to(val)
}

View File

@ -0,0 +1,12 @@
mod no_color;
mod ansi_color;
mod winapi_color;
pub mod color;
pub mod base_color;
use self::no_color::NoTerminalColor;
use self::ansi_color::ANSIColor;
use self::winapi_color::WinApiColor;

View File

@ -0,0 +1,33 @@
use Construct;
use super::color::{Color,ColorType};
use super::base_color::ITerminalColor;
/// Struct that will be instantiated when something went wrong or when an platform does not suport
/// the current concrete color inplementations.
#[derive(Debug)]
pub struct NoTerminalColor;
impl Construct for NoTerminalColor
{
fn new() -> Box<NoTerminalColor>
{
Box::from(NoTerminalColor {})
}
}
impl ITerminalColor for NoTerminalColor
{
fn set_fg(&self, fg_color: Color)
{ }
fn set_bg(&self, bg_color: Color)
{ }
fn reset(&self)
{ }
fn color_value(&self, color: Color, color_type: ColorType) -> String
{
String::from("0")
}
}

View File

@ -0,0 +1,45 @@
extern crate winapi;
use Construct;
use super::color::{Color,ColorType};
use super::base_color::ITerminalColor;
use kernel::windows_kernel::{kernel,color};
/// This struct will be used for coloring windows terminals with winapi.
#[derive(Debug)]
pub struct WinApiColor
{
original_console_color: u16,
}
impl Construct for WinApiColor
{
fn new() -> Box<WinApiColor>
{
Box::from(WinApiColor { original_console_color: kernel::get_original_console_color()})
}
}
impl ITerminalColor for WinApiColor
{
fn set_fg(&self, fg_color: Color)
{
let color_value = &self.color_value(fg_color, ColorType::Foreground);
color::set_fg_color(color_value.parse().unwrap());
}
fn set_bg(&self, bg_color: Color)
{
let color_value = &self.color_value(bg_color, ColorType::Background);
color::set_bg_color(color_value.parse().unwrap());
}
fn reset(&self)
{
color::reset(self.original_console_color);
}
fn color_value(&self, color: Color, color_type: ColorType) -> String
{
color::winapi_color_val(color,color_type).to_string()
}
}

View File

@ -0,0 +1,8 @@
mod color;
mod styles;
pub use self::color::base_color::{ITerminalColor};
pub use self::color::color::*;
pub use self::styles::objectstyle::ObjectStyle;
pub use self::styles::styledobject::StyledObject;

View File

@ -0,0 +1,2 @@
pub mod objectstyle;
pub mod styledobject;

View File

@ -0,0 +1,49 @@
use terminal_style::{ Color, StyledObject };
use std::fmt::Display;
/// This struct contains the style properties that can be applied to an displayable object.
#[derive(Clone)]
pub struct ObjectStyle
{
pub fg_color: Option<Color>,
pub bg_color: Option<Color>,
}
impl Default for ObjectStyle
{
fn default() -> ObjectStyle
{
ObjectStyle { fg_color: Some(Color::White), bg_color: Some(Color::Black) }
}
}
impl ObjectStyle
{
/// Get an `StyledObject` from the passed displayable object.
pub fn apply_to<D>(&self, val: D) -> StyledObject<D> where D: Display {
StyledObject {
object_style: self.clone(),
content: val
}
}
/// Get an instance of `ObjectStyle`
pub fn new() -> ObjectStyle
{
return ObjectStyle {fg_color: None, bg_color: None }
}
/// Set the background color of `ObjectStyle` to the passed color.
pub fn bg(mut self, color: Color) -> ObjectStyle
{
self.bg_color = Some(color);
self
}
/// Set the foreground color of `ObjectStyle` to the passed color.
pub fn fg(mut self, color: Color) -> ObjectStyle
{
self.fg_color = Some(color);
self
}
}

View File

@ -0,0 +1,72 @@
use terminal_style::{ObjectStyle, Color};
/// Struct that contains both the style and the content wits is styled.
pub struct StyledObject<V>
{
pub object_style: ObjectStyle,
pub content: V,
}
impl<D> StyledObject<D>
{
/// Paints the foreground color with the passed `Color`
///
/// #Example
///
/// ```rust
/// extern crate crossterm;
///
/// use self::crossterm::terminal_style::{paint,Color};
///
/// fn main()
/// {
/// // create an styled object with the foreground color red.
/// let styledobject = paint("I am colored red").with(Color::Red);
/// // create an styled object with the foreground color blue.
/// let styledobject1 = paint("I am colored blue").with(Color::Blue);
///
/// // print the styled objects
/// println!("{}", styledobject);
/// println!("{}", styledobject1);
/// // or print an styled object directly.
/// println!("{}", paint("I am colored green").with(Color::Green))
/// }
/// ```
pub fn with(mut self, foreground_color: Color) -> StyledObject<D>
{
self.object_style = self.object_style.fg(foreground_color);
self
}
/// Paints the background color with the passed `Color`
///
/// #Example
///
/// ```rust
/// extern crate crossterm;
///
/// use self::crossterm::terminal_style::{paint,Color};
///
/// fn main()
/// {
/// // create an styled object with the background color red.
/// let styledobject = paint("I am colored red").on(Color::Red);
/// // create an styled object with the background color blue.
/// let styledobject1 = paint("I am colored blue").on(Color::Blue);
///
/// // print the styled objects
/// println!("{}", styledobject);
/// println!("{}", styledobject1);
/// // or print an styled object directly.
/// println!("{}", paint("I am colored green").on(Color::Green))
/// }
/// ```
pub fn on(mut self, background_color: Color) -> StyledObject<D>
{
self.object_style = self.object_style.bg(background_color);
self
}
}