Skip to content

Commit

Permalink
Fix snap issues and reformat
Browse files Browse the repository at this point in the history
Add version command
  • Loading branch information
LyzardKing committed Jun 21, 2019
1 parent e73ae5e commit 62be4ce
Show file tree
Hide file tree
Showing 7 changed files with 101 additions and 59 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ build/
dist/
.cache
.pytest_cache
.mypy_cache

# Log used by setup.py
installed.log
Expand Down
5 changes: 2 additions & 3 deletions grive_indicator/UI/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ def __init__(self, debug, nocsd):
self.hb.set_show_close_button(False)
self.hb.props.title = 'Settings'
self.set_titlebar(self.hb)
self.set_decorations(0)

self.grid = Gtk.Grid(column_spacing=10, row_spacing=10)
self.add(self.grid)
Expand All @@ -63,7 +62,7 @@ def __init__(self, debug, nocsd):
label_theme = Gtk.Label("Dark Theme", xalign=1)
theme_swith = Gtk.Switch(halign=Gtk.Align.START)
# TODO Fix for custom themes
theme_swith.set_active(conf.config['DEFAULT'].getboolean('dark'))
theme_swith.set_active(conf.getBool('dark'))
theme_swith.connect('notify::active', self.on_dark_theme_activate)

label_startup = Gtk.Label("Enable on Startup", xalign=1)
Expand All @@ -78,7 +77,7 @@ def __init__(self, debug, nocsd):

label_csd = Gtk.Label("Enable CSD", xalign=1)
csd_switch = Gtk.Switch(halign=Gtk.Align.START)
csd_switch.set_active(conf.config['DEFAULT'].getboolean('use_csd'))
csd_switch.set_active(conf.getBool('use_csd'))
csd_switch.connect('notify::active', self.on_csd_activate)

label_up_speed = Gtk.Label("Limit Upload Speed", xalign=1)
Expand Down
93 changes: 57 additions & 36 deletions grive_indicator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,40 +29,47 @@

from concurrent import futures
from datetime import datetime
from gi.repository import Gtk, Gio, GLib, Notify
from gi.repository import Gtk, Gdk, Gio, GLib, Notify
from grive_indicator.UI import settings, configure
from grive_indicator.tools import ind, Config, config_file,\
is_connected, runConfigure, show_notify
is_connected, runConfigure, show_notify, get_version

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)


class GriveIndicator(Gtk.Application):

def __init__(self):
Gtk.Application.__init__(self,
application_id="org.app.grive_indicator",
flags=Gio.ApplicationFlags.FLAGS_NONE)

def do_activate(self):
parser = argparse.ArgumentParser(description='Grive Indicator.')
parser.add_argument('--folder', '-f', action='store', help='destination folder')
parser.add_argument('--debug', action='store_true', help='Debug mode without grive')
# TODO: Add auth parameter
args = parser.parse_args()
folder = args.folder
self.debug = args.debug
def __init__(self, cliArgs, *args, **kwargs):
super().__init__(*args, application_id="com.github.lyzardking.grive_indicator",
flags=Gio.ApplicationFlags.FLAGS_NONE,
**kwargs)
if cliArgs.version:
print(get_version())
exit()
self.folder = cliArgs.folder
self.debug = cliArgs.debug

def on_activate(self):
if not self.future.running():
logger.debug("Already Running: Running sync")
self.lastSync_item.set_label('Syncing...')
self.syncNow(None)
else:
logger.debug("Sync already running")

def do_startup(self):
Gtk.Application.do_startup(self)
try:
self.nocsd = not Config().getbool('use_csd')
self.nocsd = not Config().getBool('use_csd')
except Exception as e:
logger.error(e)
self.nocsd = True

self.menu_setup()
ind.set_menu(self.menu)
if folder:
runConfigure(folder=folder)
if self.folder:
runConfigure(folder=self.folder)
if not os.path.exists(config_file):
logger.debug('Setting config file %s.' % config_file)
configure.main(self.nocsd)
Expand Down Expand Up @@ -112,6 +119,7 @@ def menu_setup(self):

def refresh(self):
if is_connected() is True:
self.lastSync_item.set_label('Syncing...')
self.syncNow(None)
GLib.timeout_add_seconds(60 * int(Config().getValue('time')), self.refresh)

Expand All @@ -123,30 +131,27 @@ def syncNow(self, widget):
self.lastSync_item.set_label('Syncing...')
folder = Config().getValue('folder')
grive_cmd = ['grive']
# Uncomment the following line if testing.
# grive_cmd.append('--dry-run')
# grive_cmd = ['/snap/bin/grive-indicator.grive']
upload_speed = Config().getValue('upload_speed')
if upload_speed != '':
if upload_speed != "0":
grive_cmd.append('--upload-speed {}'.format(upload_speed))
download_speed = Config().getValue('download_speed')
if download_speed != '':
if download_speed != "0":
grive_cmd.append('--download-speed {}'.format(download_speed))
# Debug UI
if self.debug:
logger.setLevel('DEBUG')
logger.debug('Running in debug mode')
logger.debug('Emulate sync, then update label')
try:
logger.debug('Running: {}'.format(grive_cmd))
# if not self.debug:
result = subprocess.Popen(grive_cmd,
cwd=folder,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE)
result = subprocess.run(grive_cmd,
cwd=folder,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE)
notify = Config().getValue('show_notifications')
if not self.debug:
for grive_out_line in result.stdout:
grive_out_line = grive_out_line.decode()
if self.debug:
for grive_out_line in str.splitlines(result.stdout.decode()):
logger.debug('Grive log: ' + grive_out_line)
if notify:
if grive_out_line.startswith('sync'):
show_notify(grive_out_line)
Expand All @@ -161,12 +166,17 @@ def syncNow(self, widget):
pass

def openRemote(self, widget):
# Gtk.show_uri_on_window(None, "https://drive.google.com", Gdk.CURRENT_TIME)
subprocess.call(["xdg-open", "https://drive.google.com"])
Gtk.show_uri_on_window(None, "https://drive.google.com", Gdk.CURRENT_TIME)

def openLocal(self, widget):
# Gtk.show_uri_on_window(None, "file://{}".format(Config().getValue('folder')), Gdk.CURRENT_TIME)
subprocess.call(["xdg-open", "file://{}".format(Config().getValue('folder'))])
localFolder = "file://{}".format(Config().getValue('folder'))
if os.getenv("SNAP") is not None:
logger.debug("Opening {} in snap: xdg-open".format(localFolder))
subprocess.call(["xdg-open", localFolder])
else:
logger.debug("Opening {}: show_uri_on_window".format(localFolder))
Gtk.show_uri_on_window(None, localFolder, Gdk.CURRENT_TIME)
# subprocess.call(["xdg-open", "file://{}".format(Config().getValue('folder'))])

def settings(self, widget):
settings.main(self.debug, self.nocsd)
Expand All @@ -181,5 +191,16 @@ def main():
# Glib steals the SIGINT handler and so, causes issue in the callback
# https://bugzilla.gnome.org/show_bug.cgi?id=622084
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = GriveIndicator()

parser = argparse.ArgumentParser(description='Grive Indicator.')
parser.add_argument('--folder', '-f', action='store', help='Custom destination folder')
parser.add_argument('--debug', action='store_true', help='Debug mode without grive')
parser.add_argument('--version', action='store_true', help='Print the version and quit')
# TODO: Add auth parameter
args = parser.parse_args()

app = GriveIndicator(args)
# app.connect("activate", app.on_activate)
# app.connect("startup", app.do_startup)

app.run()
26 changes: 19 additions & 7 deletions grive_indicator/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,12 @@
class Config:
def __init__(self):
self.config = configparser.ConfigParser()

def config(self):
self.config.read(config_file)
return self.config

def getValue(self, key):
self.config.read(config_file)
return self.config['DEFAULT'][key]

def getbool(self, key):
self.config.read(config_file)
def getBool(self, key):
tmp = self.config['DEFAULT'][key]
if tmp.lower() == 'false':
return False
Expand All @@ -67,7 +62,6 @@ def getbool(self, key):

def setValue(self, key, value):
logger.debug('Set config {} to {}'.format(key, value))
self.config.read(config_file)
self.config['DEFAULT'][key] = value
with open(config_file, 'w') as configfile:
self.config.write(configfile)
Expand Down Expand Up @@ -176,6 +170,24 @@ def show_notify(line):
notification.show()


def get_version():
'''Get version depending if on dev or released version'''
version = open(os.path.join(os.path.dirname(__file__), 'version'), 'r', encoding='utf-8').read().strip()
if os.getenv('SNAP_REVISION'):
snap_appendix = ''
snap_rev = os.getenv('SNAP_REVISION')
if snap_rev:
snap_appendix = '+snap{}'.format(snap_rev)
return version + snap_appendix
import subprocess
try:
# use git describe to get a revision ref if running from a branch. Will append dirty if local changes
version = subprocess.check_output(["git", "describe", "--tags", "--dirty"]).decode('utf-8').strip()
except (subprocess.CalledProcessError, FileNotFoundError):
version += "+unknown"
return version


ind = AppIndicator3.Indicator.new("Grive Indicator", getIcon(),
AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
Expand Down
1 change: 1 addition & 0 deletions grive_indicator/version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
19.06
7 changes: 5 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,17 @@

setup(
name='grive-indicator',
version='1.0',
version='19.06',
url='https://github.com/LyzardKing/grive-indicator',
maintainer='Galileo Sartor',
maintainer_email='[email protected]',
description='Linux Gtk indicator to sync Google Drive via Grive',
packages=find_packages(exclude=["tests*"]),
package_data={'grive_indicator': data},
data_files=[(sys.prefix + '/share/applications', ['grive_indicator/data/grive-indicator.desktop'])] + icons,
data_files=[
('lib/python3/dist-packages/grive_indicator', ['grive_indicator/version']),
(sys.prefix + '/share/applications', ['grive_indicator/data/grive-indicator.desktop'])] +
+ icons,
entry_points={
'console_scripts': [
'grive-indicator = grive_indicator:main',
Expand Down
27 changes: 16 additions & 11 deletions snap/snapcraft.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
name: grive-indicator
version: 'master'
summary: Simple indicator for Grive sync tool
summary: Appindicator menu for Grive2
description: |
This is my-snap's description. You have a paragraph or two to tell the
most important story about your snap. Keep it under 100 words though,
we live in tweetspace and your description wants to look good in the snap
store.
Appindicator menu support for grive2.
Google Drive sync tool.
grade: stable
confinement: strict
Expand All @@ -24,7 +22,6 @@ apps:
- x11
- gnome-3-28-1804
- unity7
- network-control
environment:
XDG_DATA_DIRS: $SNAP/share:$XDG_DATA_DIRS
GSETTINGS_SCHEMA_DIR: $SNAP/share/glib-2.0/schemas
Expand All @@ -50,16 +47,13 @@ plugs:
target: $SNAP/data-dir/icons
default-provider: gtk-common-themes:icon-themes


slots:
grive-indicator-dbus:
interface: dbus
name: org.app.grive_indicator
name: com.github.lyzardking.grive_indicator
bus: session

parts:
desktop-gnome-platform:

grive-indicator:
source: .
plugin: python
Expand Down Expand Up @@ -104,4 +98,15 @@ parts:
- libgcc1
- libgcrypt20
- libstdc++6
- libyajl2
- libyajl2
desktop-gnome-platform:
source: https://github.com/ubuntu/snapcraft-desktop-helpers.git
source-subdir: gtk
plugin: make
make-parameters: ["FLAVOR=gtk3"]
build-packages:
- build-essential
- libgtk-3-dev
override-build: |
snapcraftctl build
mkdir -pv $SNAPCRAFT_PART_INSTALL/gnome-platform

0 comments on commit 62be4ce

Please sign in to comment.