~umang/indicator-stickynotes/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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/python3
# 
# Copyright © 2012-2016 Umang Varma <umang.me@gmail.com>
# 
# This file is part of indicator-stickynotes.
# 
# indicator-stickynotes 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 (at your
# option) any later version.
# 
# indicator-stickynotes 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
# indicator-stickynotes.  If not, see <http://www.gnu.org/licenses/>.

from stickynotes.backend import Note, NoteSet
from stickynotes.gui import *
import stickynotes.info
from stickynotes.info import MO_DIR, LOCALE_DOMAIN

import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, Gdk
from gi.repository import AppIndicator3 as appindicator

import os.path
import locale
import argparse
from locale import gettext as _
from functools import wraps
from shutil import copyfile, SameFileError

import socket
import sys

def save_required(f):
    """Wrapper for functions that require a save after execution"""
    @wraps(f)
    def _wrapper(self, *args, **kwargs):
        ret = f(self, *args, **kwargs)
        self.save()
        return ret
    return _wrapper

class IndicatorStickyNotes:
    def __init__(self, args = None):
        self.args = args
        # use development data file if requested
        isdev = args and args.d
        self.data_file = stickynotes.info.DEBUG_SETTINGS_FILE if isdev \
                else stickynotes.info.SETTINGS_FILE
        # Initialize NoteSet
        self.nset = NoteSet(StickyNote, self.data_file, self)
        try:
            self.nset.open()
        except FileNotFoundError:
            self.nset.load_fresh()
        except Exception as e:
            err = _("Error reading data file. Do you want to "
                "backup the current data?")
            winError = Gtk.MessageDialog(None, None, Gtk.MessageType.ERROR,
                    Gtk.ButtonsType.NONE, err)
            winError.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
                    _("Backup"), Gtk.ResponseType.ACCEPT)
            winError.set_title(_("Indicator Stickynotes"))
            resp = winError.run()
            winError.hide()
            if resp == Gtk.ResponseType.ACCEPT:
                self.backup_datafile()
            winError.destroy()
            self.nset.load_fresh()

        # If all notes were visible previously, show them now
        if self.nset.properties.get("all_visible", True):
            self.nset.showall()
        # Create App Indicator
        self.ind = appindicator.Indicator.new(
                "Sticky Notes", "indicator-stickynotes",
                appindicator.IndicatorCategory.APPLICATION_STATUS)
        # Delete/modify the following file when distributing as a package
        self.ind.set_icon_theme_path(os.path.abspath(os.path.join(
            os.path.dirname(__file__), 'Icons')))
        self.ind.set_icon("indicator-stickynotes-mono")
        self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)
        self.ind.set_title(_("Sticky Notes"))
        # Create Menu
        self.menu = Gtk.Menu()
        self.mNewNote = Gtk.MenuItem(_("New Note"))
        self.menu.append(self.mNewNote)
        self.mNewNote.connect("activate", self.new_note, None)
        self.mNewNote.show()

        s = Gtk.SeparatorMenuItem.new()
        self.menu.append(s)
        s.show()

        self.mShowAll = Gtk.MenuItem(_("Show All"))
        self.menu.append(self.mShowAll)
        self.mShowAll.connect("activate", self.showall, None)
        self.mShowAll.show()

        self.mHideAll = Gtk.MenuItem(_("Hide All"))
        self.menu.append(self.mHideAll)
        self.mHideAll.connect("activate", self.hideall, None)
        self.mHideAll.show()

        s = Gtk.SeparatorMenuItem.new()
        self.menu.append(s)
        s.show()

        self.mLockAll = Gtk.MenuItem(_("Lock All"))
        self.menu.append(self.mLockAll)
        self.mLockAll.connect("activate", self.lockall, None)
        self.mLockAll.show()

        self.mUnlockAll = Gtk.MenuItem(_("Unlock All"))
        self.menu.append(self.mUnlockAll)
        self.mUnlockAll.connect("activate", self.unlockall, None)
        self.mUnlockAll.show()

        s = Gtk.SeparatorMenuItem.new()
        self.menu.append(s)
        s.show()

        self.mExport = Gtk.MenuItem(_("Export Data"))
        self.menu.append(self.mExport)
        self.mExport.connect("activate", self.export_datafile, None)
        self.mExport.show()

        self.mImport = Gtk.MenuItem(_("Import Data"))
        self.menu.append(self.mImport)
        self.mImport.connect("activate", self.import_datafile, None)
        self.mImport.show()

        s = Gtk.SeparatorMenuItem.new()
        self.menu.append(s)
        s.show()

        self.mAbout = Gtk.MenuItem(_("About"))
        self.menu.append(self.mAbout)
        self.mAbout.connect("activate", self.show_about, None)
        self.mAbout.show()

        self.mSettings = Gtk.MenuItem(_("Settings"))
        self.menu.append(self.mSettings)
        self.mSettings.connect("activate", self.show_settings, None)
        self.mSettings.show()

        s = Gtk.SeparatorMenuItem.new()
        self.menu.append(s)
        s.show()

        self.mQuit = Gtk.MenuItem(_("Quit"))
        self.menu.append(self.mQuit)
        self.mQuit.connect("activate", Gtk.main_quit, None)
        self.mQuit.show()
        # Connect Indicator to menu
        self.ind.set_menu(self.menu)

        # Define secondary action (middle click)
        self.connect_secondary_activate()

    def new_note(self, *args):
        self.nset.new()

    def showall(self, *args):
        self.nset.showall(*args)
        self.connect_secondary_activate()

    def hideall(self, *args):
        self.nset.hideall()
        self.connect_secondary_activate()

    def connect_secondary_activate(self):
        """Define action of secondary action (middle click) depending
        on visibility state of notes."""
        if self.nset.properties["all_visible"] == True:
            self.ind.set_secondary_activate_target(self.mHideAll)
        else:
            self.ind.set_secondary_activate_target(self.mShowAll)


    @save_required
    def lockall(self, *args):
        for note in self.nset.notes:
            note.set_locked_state(True)
        
    @save_required
    def unlockall(self, *args):
        for note in self.nset.notes:
            note.set_locked_state(False)

    def backup_datafile(self):
        winChoose = Gtk.FileChooserDialog(_("Export Data"), None,
                Gtk.FileChooserAction.SAVE, (Gtk.STOCK_CANCEL,
                    Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE,
                    Gtk.ResponseType.ACCEPT))
        winChoose.set_do_overwrite_confirmation(True)
        response = winChoose.run()
        backupfile = None
        if response == Gtk.ResponseType.ACCEPT:
            backupfile =  winChoose.get_filename()
        winChoose.destroy()
        if backupfile:
            try:
                copyfile(os.path.expanduser(self.data_file), backupfile)
            except SameFileError:
                err = _("Please choose a different "
                    "destination for the backup file.")
                winError = Gtk.MessageDialog(None, None,
                        Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, err)
                winError.run()
                winError.destroy()
                self.backup_datafile()

    def export_datafile(self, *args):
        self.backup_datafile()

    def import_datafile(self, *args):
        winChoose = Gtk.FileChooserDialog(_("Import Data"), None,
                Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL,
                    Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
                    Gtk.ResponseType.ACCEPT))
        response = winChoose.run()
        backupfile = None
        if response == Gtk.ResponseType.ACCEPT:
            backupfile =  winChoose.get_filename()
        winChoose.destroy()
        if backupfile:
            try:
                with open(backupfile, encoding="utf-8") as fsock:
                    self.nset.merge(fsock.read())
            except Exception as e:
                err = _("Error importing data.")
                winError = Gtk.MessageDialog(None, None,
                        Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, err)
                winError.run()
                winError.destroy()

    def show_about(self, *args):
        show_about_dialog()

    def show_settings(self, *args):
        wSettings = SettingsDialog(self.nset)

    def save(self):
        self.nset.save()

def main():
    # Avoid duplicate process
    # From https://stackoverflow.com/questions/788411/check-to-see-if-python-script-is-running
    procLock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    try:
        procLock.bind('\0' + 'indicator-stickynotes')
    except socket.error:
        print('Indicator stickynotes already running.')
        sys.exit()

    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        locale.setlocale(locale.LC_ALL, 'C')
    # If we're running from /usr, then .mo files are not in MO_DIR.
    if os.path.abspath(__file__)[:4] == '/usr':
        # Fallback to default
        locale_dir = None
    else:
        locale_dir = os.path.join(os.path.dirname(__file__), MO_DIR)
    locale.bindtextdomain(LOCALE_DOMAIN, locale_dir)
    locale.textdomain(LOCALE_DOMAIN)

    parser = argparse.ArgumentParser(description=_("Sticky Notes"))
    parser.add_argument("-d", action='store_true', help="use the development"
            " data file")
    args = parser.parse_args()

    indicator = IndicatorStickyNotes(args)
    # Load global css for the first time.
    load_global_css()
    Gtk.main()
    indicator.save()

if __name__ == "__main__":
    main()