Browse code

Application code

Olivier Lecointre authored on 02/10/2024 00:05:42
Showing 8 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,2 @@
1
+[build]
2
+target-dir = "../../../Projects/RustBuild/rustapp"         # path of where to place all generated artifacts
0 3
new file mode 100644
... ...
@@ -0,0 +1 @@
1
+/target
0 2
new file mode 100644
... ...
@@ -0,0 +1,15 @@
1
+[package]
2
+name = "rustapp"
3
+version = "0.0.1"
4
+authors =["Olivier <olivier@cadexis.com>"]
5
+edition = "2021"
6
+
7
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8
+
9
+[dependencies]
10
+log = "0.4"
11
+simple_logger = "4.3"
12
+gtk = "0.18"
13
+gdk = "0.18"
14
+gdk-pixbuf = "0.18"
15
+appindicator3 = "0.3.0"
... ...
@@ -1,4 +1,57 @@
1
-# RUSTAPP
1
+# Rust App
2
+
3
+This is a base application to integrate with Rust and Gtk.
4
+
5
+It integrates a tray icon and some actions, with a main window which is only hiding rather than closing.
6
+
7
+The window will be un-hidden by clicking the Main menu item in the tray icon. This should also bring the window on top of the other windows. 
8
+
9
+The icon (emoticon) is present on the taskbar and also on the tray icon. However due to the limitation of the tray icon, both a ico and png file are necessary. 
10
+
11
+The build script (build.rs) is copying the icon to the destination directory.
12
+
13
+The build is not kept with the files but is set in a separate directory.
14
+
15
+```
16
+../../../Projects/RustBuild/rustapp
17
+```
18
+
19
+This path is kept in .cargo/config.toml
20
+
21
+The build script is also using the same destination directory. This script needs to be changed to use the same destination.
22
+
23
+### To run:
24
+
25
+A few dependencies needs to be used:
26
+
27
+- The trayicon widget 
28
+
29
+To build the project
30
+
31
+
32
+```
33
+cargo build
34
+```
35
+
36
+To run the project
37
+
38
+```
39
+cargo run
40
+```
41
+
42
+
43
+### Note:
44
+
45
+- The keybinder is not implemented in the GTK bindings
46
+
47
+- This project is only targetted at GTK and was only tested on Linux.
48
+
49
+
50
+### References:
51
+
52
+- https://docs.rs/appindicator3/latest/src/simple_client/simple_client.rs.html#61
53
+
54
+- https://github.com/gtk-rs/gtk3-rs/blob/master/examples/multi_window/main.rs
55
+
2 56
 
3
-This is a base application to integrate with Rust and Gtk
4 57
 
5 58
new file mode 100644
... ...
@@ -0,0 +1,40 @@
1
+/*
2
+ * build.rs
3
+ * 
4
+ * Copyright 2018-2024 Olivier Lecointre <olivier[at]cadexis[dot]com>
5
+ * 
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ * 
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+ * GNU General Public License for more details.
15
+ * 
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with this program; if not see <http://www.gnu.org/licenses/>.
18
+ * 
19
+ */
20
+
21
+use std::env;
22
+use std::fs;
23
+use std::path::Path;
24
+use std::path::PathBuf;
25
+
26
+fn get_target_path() -> PathBuf {
27
+    let _out_dir = env::var("OUT_DIR").unwrap();
28
+    let _path = Path::new(&_out_dir).join("../../../");
29
+    return PathBuf::from(_path);
30
+}
31
+
32
+fn main() {
33
+	//let _out_dir = env::var("OUT_DIR").unwrap();
34
+	let target_dir = get_target_path();
35
+    let src = "/home/olivier/vdocs/Projects/rust/rustapp/emoticon.png";//Path::join(&env::current_dir().unwrap(), "/emoticon.png");
36
+    println!("Source {:?}",src);
37
+    let dest = Path::join(Path::new(&target_dir), Path::new("emoticon.png"));
38
+    println!("Dest {:?}",dest);
39
+    fs::copy(src, dest).unwrap();
40
+}
0 41
new file mode 100644
1 42
Binary files /dev/null and b/emoticon.ico differ
2 43
new file mode 100644
3 44
Binary files /dev/null and b/emoticon.png differ
4 45
new file mode 100644
... ...
@@ -0,0 +1,188 @@
1
+/*
2
+ * main.rs
3
+ * 
4
+ * Copyright 2018-2024 Olivier Lecointre <olivier[at]cadexis[dot]com>
5
+ * 
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ * 
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+ * GNU General Public License for more details.
15
+ * 
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with this program; if not see <http://www.gnu.org/licenses/>.
18
+ * 
19
+ */
20
+
21
+use core::sync::atomic::{AtomicBool, Ordering};
22
+use glib::clone;
23
+use gtk::glib;
24
+use gtk::prelude::*;
25
+use gdk_pixbuf::prelude::PixbufLoaderExt;
26
+use gdk_pixbuf::Pixbuf;
27
+use gdk_pixbuf::PixbufLoader;
28
+use log::{info, debug};
29
+use simple_logger::SimpleLogger;
30
+use appindicator3::{prelude::*, IndicatorStatus};
31
+use appindicator3::{Indicator, IndicatorCategory};
32
+use std::cell::RefCell;
33
+use std::collections::HashMap;
34
+use std::rc::Rc;
35
+use std::fs;
36
+use std::path::PathBuf;
37
+
38
+static APP_NAME: &str = "Cadexis Rust App";
39
+static ICON_NAME: &str = "emoticon";
40
+static TRAY_NAME: &str = "CdxRustAppClientTray";
41
+
42
+static MAIN_APP_OPEN: AtomicBool = AtomicBool::new(false);
43
+
44
+pub fn set_main_app(val: bool) {
45
+    MAIN_APP_OPEN.store(val, Ordering::Relaxed)
46
+}
47
+
48
+pub fn get_main_app() -> bool {
49
+    MAIN_APP_OPEN.load(Ordering::Relaxed)
50
+}
51
+
52
+
53
+fn get_icon() -> Option<Pixbuf>{
54
+	let mut ico: Option<Pixbuf> = None;
55
+	let icon_data = include_bytes!("../emoticon.ico");
56
+	let pixbuf_loader = PixbufLoader::new();
57
+	if pixbuf_loader.write(icon_data).is_ok() {
58
+		//info!("Data Loaded");
59
+		ico = pixbuf_loader.pixbuf();
60
+	}
61
+	let _err = pixbuf_loader.close().is_ok();
62
+	return ico;
63
+}
64
+
65
+fn on_activate_main(windows : &Rc<RefCell<HashMap<usize, glib::WeakRef<gtk::Window>>>>) {
66
+	
67
+	debug!("Create Main Window");
68
+	
69
+	set_main_app(true);
70
+
71
+    let window = gtk::Window::new(gtk::WindowType::Toplevel);
72
+    
73
+    let ico = get_icon();
74
+    
75
+    window.connect_delete_event(|win,_| {
76
+		debug!("Main Window {:?}", get_main_app());
77
+		info!("Hiding Window {:?}", "App");
78
+		//set_main_app(false);
79
+		win.hide();
80
+		return true.into();
81
+	});
82
+    window.set_title(APP_NAME);
83
+    window.set_default_size(800, 600);
84
+    if ico.is_some() {
85
+		//info!("Icon Found");
86
+		window.set_icon(ico.as_ref());
87
+	}
88
+	
89
+    let button = gtk::Button::with_label("Hide Windows when clicked!");
90
+    //button.set_default_size(80, 60);
91
+    // … which closes the window when clicked
92
+    button.connect_clicked(clone!(@weak window => move |_| {
93
+		debug!("Main Window {:?}", get_main_app());
94
+		info!("Hiding Window {:?}", "App");
95
+		window.hide();
96
+		//set_main_app(false);
97
+	}));
98
+    
99
+    let box_ = gtk::Box::new(gtk::Orientation::Vertical, 1);
100
+	box_.pack_start(&button,false,false,100); 
101
+    // … with a button in it …
102
+    window.set_child(Some(&box_));
103
+    //window.present();
104
+    window.show_all();
105
+    
106
+    windows.borrow_mut().insert(1, window.downgrade());
107
+}
108
+
109
+fn show_main_window(windows : &Rc<RefCell<HashMap<usize, glib::WeakRef<gtk::Window>>>>) {
110
+	debug!("Main app {:?}", get_main_app()); 
111
+	if get_main_app() {
112
+		for window in windows.borrow().values() {
113
+            if let Some(w) = window.upgrade() {
114
+				debug!("Show window"); 
115
+                w.show();
116
+                w.hide();
117
+                w.show();
118
+                set_main_app(true);
119
+            }
120
+        }
121
+		return;
122
+	}	
123
+	on_activate_main(&windows);
124
+}
125
+
126
+pub fn get_string(_value: &Option<String>) -> String {
127
+	match _value {
128
+	  Some(key) => key.clone(),
129
+	  None => String::from("")
130
+	}
131
+}
132
+
133
+pub fn resolve_path(_path : Option<String>) -> Option<String> {
134
+		if _path.is_none() {
135
+			return None;
136
+		}
137
+		let ppath = get_string(&_path);
138
+		let absolute = fs::canonicalize(PathBuf::from(ppath.clone())).ok();
139
+		if absolute.is_none() {
140
+			return _path;
141
+		}
142
+		let spath = absolute.clone().unwrap();
143
+		if !spath.exists() {
144
+			return Some(spath.to_str().unwrap().to_string());
145
+		}
146
+		return Some(spath.to_str().unwrap().to_string());
147
+}
148
+
149
+fn main() {
150
+	SimpleLogger::new().init().unwrap();
151
+	info!("Starting app {:?}", APP_NAME);
152
+    let _ = gtk::init();
153
+    
154
+    let windows: Rc<RefCell<HashMap<usize, glib::WeakRef<gtk::Window>>>> = Rc::new(RefCell::new(HashMap::new()));
155
+	
156
+	show_main_window(&windows);
157
+    
158
+    let icon_path = resolve_path(Some(String::from("."))).unwrap();
159
+	info!("Icon path {:?}", icon_path);
160
+    
161
+	let indicator = Indicator::with_path(TRAY_NAME, ICON_NAME, IndicatorCategory::ApplicationStatus,icon_path.as_str());
162
+   
163
+    indicator.set_status(IndicatorStatus::Active);
164
+    indicator.set_title(Some(APP_NAME));
165
+    let menu = gtk::Menu::new();
166
+    let item1 = gtk::MenuItem::with_label("Main");
167
+    item1.connect_activate(glib::clone!(@weak windows => move |_| {
168
+        show_main_window(&windows);
169
+    }));
170
+
171
+    menu.append(&item1);
172
+    item1.show();
173
+    
174
+    let item2= gtk::MenuItem::with_label("Exit");
175
+    item2.connect_activate(
176
+		|_| {
177
+      		info!("Exiting App {:?}", APP_NAME);
178
+			gtk::main_quit();
179
+        }
180
+	);
181
+	menu.append(&item2);
182
+    item2.show();
183
+    
184
+    indicator.set_secondary_activate_target(Some(&item1));
185
+    indicator.set_menu(Some(&menu));
186
+    
187
+	gtk::main();
188
+}