~vlijm/wswitcher/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python3
from gi.repository import Gtk, Pango
import getpass
import os
import subprocess
import signal
import sys

"""
UNITY WallPaperSwitcher
Copyright (C) 2015  Jacob Vlijm
contact: vlijm@planet.nl
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
should have received a copy of the GNU General Public License along with this
program.  If not, see <http://www.gnu.org/licenses/>.
"""
       
class InterFace(Gtk.Window):

    def __init__(self):

        dirlist = setup_dirs()
        wswitcher_prefs = dirlist[0]
        self.config_dir = dirlist[1]
        
        # docsdir = "/opt/wswitcher/docs"
        docsdir = "/home/jacob/Bureaublad/wallSwitcher/lswitcher-0.9.9/docs" ##
        self.helpfile = docsdir+"/help"
        self.aboutfile = docsdir+"/about"

        self.curr_set = wswitcher_prefs+"/wswitcher_prefs"
        self.user = getpass.getuser()

        Gtk.Window.__init__(self, title="Unity WallPaperSwitcher")
        maingrid = Gtk.Grid()
        self.add(maingrid)
        maingrid.set_border_width(10)

        image = Gtk.Image()
        # image.set_from_file("/opt/wswitcher/icon/lsw_64.png")
        image.set_from_file("/home/jacob/Bureaublad/wallSwitcher/lswitcher-0.9.9/icon/wsw_64.png") #
        maingrid.attach(image, 0, 0, 1, 1)

        iconsep = Gtk.Grid()
        maingrid.attach(iconsep, 1, 0, 1, 1)
        iconsep.set_border_width(10)

        controlsgrid = Gtk.Grid()
        maingrid.attach(controlsgrid, 1, 0, 2, 1)
        maingrid.set_column_homogeneous(True)

        self.check1 = Gtk.CheckButton("Start on login")
        self.check1.connect("toggled", self.toggle_autostart)
        self.check1.set_active(self.read_settings())
        self.check1.set_tooltip_text("Add to Startup Applications")
        controlsgrid.attach(self.check1, 0, 0, 10, 1)

        switchsep = Gtk.Grid()
        controlsgrid.attach(switchsep, 0, 1, 1, 1)
        switchsep.set_border_width(5)

        switch = Gtk.Switch()
        switch.connect("notify::active", self.toggle_run)
        checkruns = self.test_ifruns()
        if checkruns != []:
            switch.set_active(True)
        else:
            switch.set_active(False)
        switch.set_tooltip_text("Start/Stop WallPaperSwitcher")
        controlsgrid.attach(switch, 0, 2, 1, 1)  

        topsep = Gtk.Grid()
        maingrid.attach(topsep, 0, 1, 1, 1)
        topsep.set_border_width(5)

        scrolledwindow = Gtk.ScrolledWindow()
        scrolledwindow.set_hexpand(True)
        scrolledwindow.set_vexpand(True)
        scrolledwindow.set_min_content_height(100)
        maingrid.attach(scrolledwindow, 0, 2, 4, 1)

        self.textfield = Gtk.TextView()
        self.textbuffer = self.textfield.get_buffer()
        self.textfield.set_wrap_mode(Gtk.WrapMode.WORD)
        self.textfield.set_editable(False)
        self.textfield.modify_font(Pango.FontDescription('Ubuntu Mono 12'))
        scrolledwindow.add(self.textfield)

        bottomsep = Gtk.Grid()
        maingrid.attach(bottomsep, 3, 5, 1, 1)
        bottomsep.set_border_width(5)

        quitbutton = Gtk.Button("_Close", use_underline=True)
        quitbutton.connect("clicked", self.on_close_clicked)
        quitbutton.set_size_request(75,20)
        maingrid.attach(quitbutton, 3, 7, 1, 1)

        aboutbutton = Gtk.Button("_About", use_underline=True)
        aboutbutton.connect("clicked", self.show_about)
        aboutbutton.set_size_request(60,20)
        maingrid.attach(aboutbutton, 0, 6, 1, 1)

        helpbutton = Gtk.Button("_Help", use_underline=True)
        helpbutton.connect("clicked", self.show_help)
        helpbutton.set_size_request(60,20)
        maingrid.attach(helpbutton, 1, 6, 1, 1)
        
        self.show_help()

    def toggle_autostart(self, widget):
        dtfile = self.config_dir+"/autostart/wswitcher.desktop"
        newstate = self.check1.get_active()
        if newstate == False:
            new_write = "off"
            try:
                os.remove(dtfile)
            except FileNotFoundEror:
                pass
        elif newstate == True:
            new_write = "on"
            content = [
                "[Desktop Entry]",
                "Name=WallPaperSwitcher",
                'Exec=/bin/bash -c "sleep 10&&/opt/wswitcher/wswitcher/wswitcher_run"',
                "Type=Application",
                "X-GNOME-Autostart-enabled=true",
                ]
            with open(dtfile, "wt") as out:
                for l in content:
                    out.write(l+"\n")
        open(self.curr_set, "wt").write(new_write)

    def toggle_run(self, switch, gparam):
        runs = switch.get_active()
        pids = self.test_ifruns()
        if all([runs == False, len(pids) != 0]):   
            self.stop_run(pids)
        elif all([runs == True, len(pids) == 0]):
            self.start_run()

    def stop_run(self, pids):
        for pid in pids:
            os.kill(int(pid), signal.SIGQUIT)
        subprocess.Popen(["notify-send", "WallPaperSwitcher is stopped"])

    def start_run(self):
        # subprocess.Popen(["/opt/wswitcher/wswitcher/wswitcher_run"])
        subprocess.Popen(["/home/jacob/Bureaublad/wallSwitcher/lswitcher-0.9.9/code/wswitcher_run"])
        subprocess.Popen(["notify-send", "WallPaperSwitcher is running"])
                        
    def test_ifruns(self):
        return [l.split()[0].strip() for l in subprocess.check_output(
            ["ps", "-u", self.user, "ww"]
            ).decode("utf-8").splitlines() if "wswitcher_run" in l]

    def show_help(self, *args):
        self.textbuffer.set_text(open(self.helpfile).read())

    def show_about(self, *args):
        self.textbuffer.set_text(open(self.aboutfile).read())

    def on_close_clicked(self, button):
        Gtk.main_quit()

    def read_settings(self):
        if not os.path.exists(self.curr_set):
            return False
        else:
            curr_startup = open(self.curr_set).read()
            if "on" in curr_startup:
                return True
            else:
                return False

def setup_dirs():
    home = os.environ["HOME"]
    config_dir = home+"/.config"
    autostart_dir = config_dir+"/autostart"
    wswitcher_prefs = config_dir+"/wswitcher"
    for dr in [config_dir, autostart_dir, wswitcher_prefs]:
        if not os.path.exists(dr):
            os.makedirs(dr)
    return [wswitcher_prefs, config_dir]

def toggle_cli():
    setup_dirs()
    runs = InterFace().test_ifruns()
    if len(runs) == 0:
        InterFace().start_run()
        print("wswitcher running with pid "+str(InterFace().test_ifruns()[0]))
    else:
        InterFace().stop_run(runs)
        print("terminated wswitcher with pid "+str(runs[0])+"")

try:
    arg = sys.argv[1]
except IndexError:
    window = InterFace()
    window.connect("delete-event", Gtk.main_quit)
    window.set_default_size(330, 330)
    window.set_resizable(False)
    window.show_all()
    Gtk.main()
else:
    if arg == "-toggle":
        toggle_cli()
    else:
        print("invalid argument: "+arg+
              "should be 'toggle' or no argument")