#!/usr/bin/env python3

#import birchscript
import os
import os.path
import shutil
import sys
import subprocess
import time

# Wrapper for gedit. Forces gedit to open a new
# window for each file.

# This is harder than it sounds. If we just try to open each 
# new file in a new window using '--new-window',
# while other threads of gedit are running, for some 
# reason, gedit can't get to the file before it is deleted by GDE.
# The workaround is to rename the file 
# gedit is a stupidly dumbed down program. The only 
# reason we are using it is that it is probably the most
# commonly-distributed text editor in Linux. 
#
# Renaming the file creates a new problem, being that 
# we now need to explicitly remove the temporary file.
# If we do that too quickly, gedit doesn't have time to
# find the temporary file and read it into memory. Therefore,
# we need to make the script sleep a bit before removing
# the temporary file.
# What a hack!
""" ensure that there are enough command line arguments to parse """
if len(sys.argv) < 2:
    print("Usage: gedit_wrapper.py  FILE");
    exit();

TMP_FILENAME  = 'tmp_' + str(os.getpid())

shutil.copyfile(sys.argv[1], TMP_FILENAME)
#birchscript.Cleanrun([['gedit', '--new-window', TMP_FILENAME]], [TMP_FILENAME], True)
p = subprocess.Popen(['gedit', '--new-window', '-s', TMP_FILENAME])
p.wait()
time.sleep(10)
os.remove(TMP_FILENAME)
