Source

Kephra / lib / Kephra / File.pm

use strict;
use warnings;
use File::Spec;
use Kephra::API;
use Kephra::App::Panel::Editor;
use Kephra::DocumentStash;

package Kephra::File;

Kephra::CommandList::register_cmd_namespace('file');
Kephra::CommandList::register_cmd({
 '+-new'   => {sub => 'new',          label =>' New',   keys => 'ctrl+n'},
 '+-open'  => {sub => 'open',         label => 'Open',  keys => 'ctrl+o'},
 '+-reload'=> {sub => 'reload_active',label => 'Reload',keys => 'ctrl+shift+o'},
 '+-save'  => {sub => 'save_active',  label => 'Save',  keys => 'ctrl+s'},
 '+-close' => {sub => 'close_active', label => 'Close', keys => 'ctrl+q'},
});

sub normalize_name {
	my $file = shift;
	return unless $file;

	$file = File::Spec->canonpath($file);
	local $/ = "\r\n";
	chomp($file);
	return $file;
}

sub new  { Kephra::App::Panel::Editor::create_document() }
sub open {
	# open dialog if no file was given
	$_[0] = Kephra::App::Dialog::get_file_open() unless @_;

	# new doc for each file name
	for my $file (@_){
		$file = normalize_name( $file );
		next unless $file and -e $file;

		# raise tab if doc is alread open
		Kephra::App::Panel::Editor::raise_document($file), next
		  if Kephra::DocumentStash::file_loaded($file);

		my $doc = Kephra::App::Panel::Editor::create_document($file);
		next unless ref $doc eq 'Kephra::Document';
		CORE::open my $FH, '<', $file;
		my $file_content = do { local $/; <$FH> };
		my $ed = $doc->editor;
		$ed->SetText( $file_content ) if $file_content;
		$ed->EmptyUndoBuffer;
		$ed->SetSavePoint;
	}
}
sub reload {
	for my $doc (@_){
		next unless ref $doc eq 'Kephra::Document'and -e $doc->file_path;
		CORE::open my $FH, '<', $doc->file_path;
		my $file_content = do { local $/; <$FH> };
		my $ed = $doc->editor;
		$ed->SetText( $file_content ) if $file_content;
	}
}
sub reload_active { reload( Kephra::API::document() ) }
sub reload_all    { reload( Kephra::API::all_documents()   ) }

sub save {
	for my $doc (@_){
		next unless ref $doc eq 'Kephra::Document'and -e $doc->file_path;
		CORE::open my $FH, '>', $doc->file_path;
		print $FH $doc->editor->GetText;
	}
}
sub save_active { save( Kephra::API::document() ) }
sub save_all    { save( Kephra::API::all_documents()   ) }


sub close_active {
	my $doc = Kephra::API::document();
	return unless $doc;
	Kephra::App::Panel::Editor::remove_document( $doc );
}
sub close_other  {}
sub close_all    {}

1;