1 //===========================================
2 //  Lumina-DE source code
3 //  Copyright (c) 2016, Ken Moore
4 //  Available under the 3-clause BSD license
5 //  See the LICENSE file for full details
6 //===========================================
7 #ifdef __linux__
8 #include <QDebug>
9 #include "LuminaOS.h"
10 #include <unistd.h>
11 #include <stdio.h> // Needed for BUFSIZ
12 
13 //can't read xbrightness settings - assume invalid until set
14 static int screenbrightness = -1;
15 
OSName()16 QString LOS::OSName(){ return "Gentoo Linux"; }
17 
18 //OS-specific prefix(s)
19 // NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in
LuminaShare()20 QString LOS::LuminaShare(){ return (L_SHAREDIR+"/lumina-desktop/"); } //Install dir for Lumina share files
AppPrefix()21 QString LOS::AppPrefix(){ return "/usr/"; } //Prefix for applications
SysPrefix()22 QString LOS::SysPrefix(){ return "/"; } //Prefix for system
23 
24 //OS-specific application shortcuts (*.desktop files)
ControlPanelShortcut()25 QString LOS::ControlPanelShortcut(){ return ""; } //system control panel
AppStoreShortcut()26 QString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + "/share/applications/porthole.desktop"; } //graphical app/pkg manager
27 //OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )
RSSFeeds()28 QStringList LOS::RSSFeeds(){ return QStringList(); }
29 
30 // ==== ExternalDevicePaths() ====
ExternalDevicePaths()31 QStringList LOS::ExternalDevicePaths(){
32   /* Returns: QStringList[<type>::::<filesystem>::::<path>]
33      Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]
34      df is much better for this than mount, because it skips
35      all non-physical devices (like bind-mounts from schroot)
36      so they are not listed in lumina-fm */
37   QStringList devs = LUtils::getCmdOutput("df --output=source,fstype,target");
38   //Now check the output
39   for(int i=0; i<devs.length(); i++){
40     if(devs[i].startsWith("/dev/")){
41       devs[i] = devs[i].simplified();
42       QString type = devs[i].section(" on ",0,0);
43       type.remove("/dev/");
44       //Determine the type of hardware device based on the dev node
45       if(type.startsWith("sd") || type.startsWith("nvme")){ type = "HDRIVE"; }
46       else if(type.startsWith("sr")){ type="DVD"; }
47       else if(type.contains("mapper")){ type="LVM"; }
48       else{ type = "UNKNOWN"; }
49       //Now put the device in the proper output format
50       devs[i] = type + "::::" + devs[i].section(" ",1,1) + "::::" + devs[i].section(" ",2,2);
51     }else{
52       //invalid device - remove it from the list
53       devs.removeAt(i);
54       i--;
55     }
56   }
57   return devs;
58 }
59 
60 //Read screen brightness information
ScreenBrightness()61 int LOS::ScreenBrightness(){
62    //Returns: Screen Brightness as a percentage (0-100, with -1 for errors)
63   if(screenbrightness==-1){
64     if(QFile::exists(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness")){
65       int val = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness").join("").simplified().toInt();
66       screenbrightness = val;
67     }
68   }
69   return screenbrightness;
70 
71 }
72 
73 //Set screen brightness
setScreenBrightness(int percent)74 void LOS::setScreenBrightness(int percent){
75   //ensure bounds
76   if(percent<0){percent=0;}
77   else if(percent>100){ percent=100; }
78   // float pf = percent/100.0; //convert to a decimel
79   //Run the command
80   QString cmd = "xbacklight -set %1";
81   // cmd = cmd.arg( QString::number( int(65535*pf) ) );
82   cmd = cmd.arg( QString::number( percent ) );
83   int ret = LUtils::runCmd(cmd);
84   //Save the result for later
85   if(ret!=0){ screenbrightness = -1; }
86   else{ screenbrightness = percent; }
87   LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness", QStringList() << QString::number(screenbrightness), true);
88 
89 }
90 
91 //Read the current volume
audioVolume()92 int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors)
93 QString info = LUtils::getCmdOutput("amixer get Master").join("").simplified();;
94   int out = -1;
95   int start_position, end_position;
96   QString current_volume;
97   if(!info.isEmpty()){
98      start_position = info.indexOf("[");
99      start_position++;
100      end_position = info.indexOf("%");
101      current_volume = info.mid(start_position, end_position - start_position);
102      out = current_volume.toInt();
103   }
104   return out;
105 
106 }
107 
108 //Set the current volume
setAudioVolume(int percent)109 void LOS::setAudioVolume(int percent){
110   if(percent<0){percent=0;}
111   else if(percent>100){percent=100;}
112   // QString info = "amixer -c 0 sset Master,0 " + QString::number(percent) + "%";
113   QString info = "amixer set Master " + QString::number(percent) + "%";
114   if(!info.isEmpty()){
115     //Run Command
116     LUtils::runCmd(info);
117   }
118 
119 }
120 
121 //Change the current volume a set amount (+ or -)
changeAudioVolume(int percentdiff)122 void LOS::changeAudioVolume(int percentdiff){
123   int old_volume = audioVolume();
124   int new_volume = old_volume + percentdiff;
125   if (new_volume < 0)
126       new_volume = 0;
127   if (new_volume > 100)
128       new_volume = 100;
129   qDebug() << "Setting new volume to: " << new_volume;
130   setAudioVolume(new_volume);
131 }
132 
133 //Check if a graphical audio mixer is installed
hasMixerUtility()134 bool LOS::hasMixerUtility(){
135   return QFile::exists(LOS::AppPrefix() + "bin/pavucontrol");
136 }
137 
138 //Launch the graphical audio mixer utility
startMixerUtility()139 void LOS::startMixerUtility(){
140   QProcess::startDetached(LOS::AppPrefix() + "bin/pavucontrol");
141 }
142 
143 //Check for user system permission (shutdown/restart)
userHasShutdownAccess()144 bool LOS::userHasShutdownAccess(){
145   return QProcess::startDetached("dbus-send --system --print-reply=literal \
146   --type=method_call --dest=org.freedesktop.ConsoleKit \
147   /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.CanPowerOff");
148 }
149 
150 //Check for whether the system is safe to power off (no updates being perfomed)
systemPerformingUpdates()151 bool LOS::systemPerformingUpdates(){
152   return false; //Not implemented yet
153 }
154 
155 //Return the details of any updates which are waiting to apply on shutdown
systemPendingUpdates()156 QString LOS::systemPendingUpdates(){
157   return "";
158 }
159 
160 //System Shutdown
systemShutdown(bool)161 void LOS::systemShutdown(bool){ //start poweroff sequence
162   //INPUT: skip updates (true/false)
163   QProcess::startDetached("dbus-send --system --print-reply \
164   --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \
165   org.freedesktop.ConsoleKit.Manager.PowerOff boolean:true");
166 }
167 
168 //System Restart
systemRestart(bool)169 void LOS::systemRestart(bool){ //start reboot sequence
170   //INPUT: skip updates (true/false)
171   QProcess::startDetached("dbus-send --system --print-reply \
172   --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \
173   org.freedesktop.ConsoleKit.Manager.Reboot boolean:true");
174 }
175 
176 //Check for suspend support
systemCanSuspend()177 bool LOS::systemCanSuspend(){
178   return QProcess::startDetached("dbus-send --system --print-reply=literal \
179   --type=method_call --dest=org.freedesktop.ConsoleKit \
180   /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.CanSuspend");
181 }
182 
183 //Put the system into the suspend state
systemSuspend()184 void LOS::systemSuspend(){
185   QProcess::startDetached("dbus-send --system --print-reply \
186   --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \
187   org.freedesktop.ConsoleKit.Manager.Suspend boolean:true");
188 }
189 
190 //Battery Availability
hasBattery()191 bool LOS::hasBattery(){
192   QString my_status = LUtils::getCmdOutput("acpi -b").join("");
193   bool no_battery = my_status.contains("No support");
194   if (no_battery) return false;
195   return true;
196 }
197 
198 //Battery Charge Level
batteryCharge()199 int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error
200   QString my_status = LUtils::getCmdOutput("acpi -b").join("");
201   int my_start = my_status.indexOf("%");
202   // get the number right before the % sign
203   int my_end = my_start;
204   my_start--;
205   while ( (my_status[my_start] != ' ') && (my_start > 0) )
206       my_start--;
207   my_start++;
208   int my_charge = my_status.mid(my_start, my_end - my_start).toInt();
209   if ( (my_charge < 0) || (my_charge > 100) ) return -1;
210   return my_charge;
211 }
212 
213 //Battery Charging State
214 // Many possible values are returned if the laptop is plugged in
215 // these include "Unknown, Full and No support.
216 // However, it seems just one status is returned when running
217 // on battery and that is "Discharging". So if the value we get
218 // is NOT Discharging then we assume the battery is charging.
batteryIsCharging()219 bool LOS::batteryIsCharging(){
220   QString my_status = LUtils::getCmdOutput("acpi -b").join("");
221   bool discharging = my_status.contains("Discharging");
222   if (discharging) return false;
223   return true;
224 }
225 
226 //Battery Time Remaining
batterySecondsLeft()227 int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining
228   return 0; //not implemented yet for Linux
229 }
230 
231 //File Checksums
Checksums(QStringList filepaths)232 QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file
233   QStringList info = LUtils::getCmdOutput("md5sum \""+filepaths.join("\" \"")+"\"");
234   for(int i=0; i<info.length(); i++){
235     // first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput
236     if( info[i].startsWith("md5sum:") || info[i].isEmpty()){ info.removeAt(i); i--; }
237     else{
238       //Strip out the extra information
239       info[i] = info[i].section(" ",0,0);
240     }
241   }
242  return info;
243 }
244 
245 //file system capacity
FileSystemCapacity(QString dir)246 QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command
247   QStringList mountInfo = LUtils::getCmdOutput("df -h \"" + dir + "\"");
248   QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;
249   //output: 200G of 400G available on /mount/point
250   QString capacity = mountInfo[1].section(" ",3,3, skipEmpty) + " of " + mountInfo[1].section(" ",1,1, skipEmpty) + " available on " +  mountInfo[1].section(" ",5,5, skipEmpty);
251   return capacity;
252 }
253 
CPUTemperatures()254 QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example)
255   QStringList temp = LUtils::getCmdOutput("acpi -t").filter("degrees");
256   for(int i=0; i<temp.length(); i++){
257     if(temp[i].startsWith("Thermal")){
258       temp[i] = temp[i].section(" ", 4, 6);
259     }else{
260       temp.removeAt(i); i--;
261     }
262   }
263   if(temp.isEmpty()) {
264     temp << "Not available";
265   }
266   return temp;
267 }
268 
CPUUsagePercent()269 int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)
270   QStringList info = LUtils::getCmdOutput("top -bn1").filter("Cpu(s)");
271   if(info.isEmpty()){ return -1; }
272   QString idle = info.first().section(" ", 7, 7, QString::SectionSkipEmpty);
273   if(idle.isEmpty()){ return -1; }
274   else{
275     return (100 - idle.toDouble());
276   }
277 }
278 
MemoryUsagePercent()279 int LOS::MemoryUsagePercent(){
280   QStringList mem = LUtils::getCmdOutput("top -bn1").filter("Mem :");
281   if(mem.isEmpty()){ return -1; }
282   double fB = 0; //Free Bytes
283   double uB = 0; //Used Bytes
284   fB = mem.first().section(" ", 5, 5, QString::SectionSkipEmpty).toDouble();
285   uB = mem.first().section(" ", 7, 7, QString::SectionSkipEmpty).toDouble();
286   double per = (uB/(fB+uB)) * 100.0;
287   return qRound(per);
288 }
289 
DiskUsage()290 QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device
291   QStringList info = LUtils::getCmdOutput("iostat -dx -N");
292   if(info.length()<3){ return QStringList(); } //nothing from command
293   QStringList labs = info[1].split(" ",QString::SkipEmptyParts);
294   QStringList out;
295   QString fmt = "%1: %2 %3";
296   for(int i=2; i<info.length(); i++){ //skip the first two lines, just labels
297     info[i].replace("\t"," ");
298     if(info[i].startsWith("Device:")){ labs = info[i].split(" ", QString::SkipEmptyParts); }//the labels for each column
299     else{
300       QStringList data = info[i].split(" ",QString::SkipEmptyParts); //data[0] is always the device
301       if(data.length()>2 && labs.length()>2){
302         out << fmt.arg(data[0], data[3]+" "+labs[3], data[4]+" "+labs[4]);
303       }
304     }
305   }
306 
307   return out;
308 }
309 #endif
310