"""
Toggle_ReadOnly.py - A Jython macro for jEdit that toggles 
a file's read-only flag.  Works on Windows and Linux.

Copyright (C) 2002 Ollie Rutherfurd <oliver@rutherfurd.net>

$Id: Toggle_ReadOnly.py 40 2003-04-14 17:16:57Z oliver $
"""

from java.lang import Runnable, Runtime
from javax.swing import SwingUtilities
from org.gjt.sp.jedit import Macros
from org.gjt.sp.jedit import OperatingSystem as OS

major,minor,revision = map(int,jEdit.getBuild().split('.')[:-1])


class BufferStatusChecker(Runnable):

    def __init__(self,view):
        self.view = view

    def run(self):
        jEdit.checkBufferStatus(self.view)
        self.view = None


class Toggler(Runnable):

	def __init__(self,cmd,editPane):
		self.cmd = cmd
		self.editPane = editPane

	def run(self):
		process = Runtime.getRuntime().exec(self.cmd)
		process.waitFor()
		# jEdit 4.2pre1 removed Buffer.checkModTime()
		checkModTime = getattr(self.editPane.getBuffer(), 'checkModTime', None)
		if checkModTime:
			if major == 4 and (minor == 1 and revision < 8):
				checkModTime(self.editPane.getView())
			else:
				checkModTime(self.editPane)
		else:
			SwingUtilities.invokeLater(BufferStatusChecker(self.editPane.getView()))
		self.editPane = None


def toggleReadOnly(editPane):

	b = editPane.getBuffer()
	v = editPane.getView()

	# make sure we've got a local file
	if not b.getVFS().getName() == 'file':
		Macros.error(v,'Sorry, this macro only works on local files.')
		return

	# get current read-only status
	ro = b.isReadOnly()

	if OS.isUnix():
		cmd = 'chmod %sw %s' % ([ro and '+' or '-'][0], b.getPath(),)
	elif OS.isWindows():
		cmd = 'ATTRIB.EXE %sR "%s"' % ([ro and '-' or '+'][0], b.getPath(),)
	else:
		Macros.error(v, 'Sorry, this macro only works on Windows and Unix.')
		return

	# invoke native command in a separate thread
	SwingUtilities.invokeLater(Toggler(cmd,editPane))


if __name__ in ('__main__','main'):
	toggleReadOnly(init.editPane)

# :indentSize=4:lineSeparator=\n:noTabs=false:tabSize=4:

