Skip to content

Commit

Permalink
FIXED: abort program when ~/.config/virtscreen does not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
kbumsik committed Nov 9, 2018
1 parent 6759ac6 commit bd115a2
Showing 1 changed file with 31 additions and 28 deletions.
59 changes: 31 additions & 28 deletions virtscreen/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,40 +79,22 @@ def on_exit(self, signum=None, frame=None):
signal.signal(sig, on_exit)

args = vars(parser.parse_args())
# Enable logging
if args['log'] is None:
args['log'] = 'WARNING'
log_level = getattr(logging, args['log'].upper(), None)
if not isinstance(log_level, int):
error('Please choose a correct python logging level')
sys.exit(1)
# When logging level is INFO or lower, print logs in terminal
# Otherwise log to a file
log_to_file = True if log_level > logging.INFO else False
FORMAT = "[%(levelname)s:%(filename)s:%(lineno)s:%(funcName)s()] %(message)s"
logging.basicConfig(level=log_level, format=FORMAT,
**({'filename': LOGGING_PATH} if log_to_file else {}))
if log_to_file:
logger = logging.getLogger()
handler = RotatingFileHandler(LOGGING_PATH, mode='a', maxBytes=1024*4, backupCount=1)
logger.addHandler(handler)
logging.info('logging enabled')
del args['log']
logging.info(f'{args}')
cli_args = ['auto', 'left', 'right', 'above', 'below', 'portrait', 'hidpi']
# Start main
if any(args.values()):
if any((value and arg in cli_args) for arg, value in args.items()):
main_cli(args)
else:
main_gui()
main_gui(args)
error('Program should not reach here.')
sys.exit(1)

def check_env(msg: Callable[[str], None]) -> None:
"""Check environments before start"""
def check_env(args: argparse.Namespace, msg: Callable[[str], None]) -> None:
"""Check environments and arguments before start. This also enable logging"""
if os.environ.get('XDG_SESSION_TYPE', '').lower() == 'wayland':
msg("Currently Wayland is not supported")
sys.exit(1)
if not HOME_PATH:
# Check ~/.config/virtscreen
if not HOME_PATH: # This is set in path.py
msg("Cannot detect home directory.")
sys.exit(1)
if not os.path.exists(HOME_PATH):
Expand All @@ -121,17 +103,38 @@ def check_env(msg: Callable[[str], None]) -> None:
except:
msg("Cannot create ~/.config/virtscreen")
sys.exit(1)
# Check x11vnc
if not shutil.which('x11vnc'):
msg("x11vnc is not installed.")
sys.exit(1)
# Enable logging
if args['log'] is None:
args['log'] = 'WARNING'
log_level = getattr(logging, args['log'].upper(), None)
if not isinstance(log_level, int):
error('Please choose a correct python logging level')
sys.exit(1)
# When logging level is INFO or lower, print logs in terminal
# Otherwise log to a file
log_to_file = True if log_level > logging.INFO else False
FORMAT = "[%(levelname)s:%(filename)s:%(lineno)s:%(funcName)s()] %(message)s"
logging.basicConfig(level=log_level, format=FORMAT,
**({'filename': LOGGING_PATH} if log_to_file else {}))
if log_to_file:
logger = logging.getLogger()
handler = RotatingFileHandler(LOGGING_PATH, mode='a', maxBytes=1024*4, backupCount=1)
logger.addHandler(handler)
logging.info('logging enabled')
del args['log']
logging.info(f'{args}')
# Check if xrandr is correctly parsed.
try:
test = XRandR()
except RuntimeError as e:
msg(str(e))
sys.exit(1)

def main_gui():
def main_gui(args: argparse.Namespace):
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
loop = QEventLoop(app)
Expand All @@ -144,7 +147,7 @@ def dialog(message: str) -> None:
if not QSystemTrayIcon.isSystemTrayAvailable():
dialog("Cannot detect system tray on this system.")
sys.exit(1)
check_env(dialog)
check_env(args, dialog)

app.setApplicationName("VirtScreen")
app.setWindowIcon(QIcon(ICON_PATH))
Expand All @@ -170,7 +173,7 @@ def dialog(message: str) -> None:
def main_cli(args: argparse.Namespace):
loop = asyncio.get_event_loop()
# Check the environment
check_env(print)
check_env(args, print)
if not os.path.exists(CONFIG_PATH):
error("Configuration file does not exist.\n"
"Configure a virtual screen using GUI first.")
Expand Down

0 comments on commit bd115a2

Please sign in to comment.