Skip to content

Commit

Permalink
rename notes_history.py to comments.py
Browse files Browse the repository at this point in the history
  • Loading branch information
jborbely committed Oct 15, 2019
1 parent 476d206 commit 6e78a69
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 79 deletions.
8 changes: 8 additions & 0 deletions docs/_api/msl.qt.widgets.comments.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
msl.qt.widgets.comments module
==============================

.. automodule:: msl.qt.widgets.comments
:members:
:undoc-members:
:show-inheritance:
:exclude-members: staticMetaObject
8 changes: 0 additions & 8 deletions docs/_api/msl.qt.widgets.notes_history.rst

This file was deleted.

2 changes: 1 addition & 1 deletion docs/_api/msl.qt.widgets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ Submodules
msl.qt.widgets.button
msl.qt.widgets.led
msl.qt.widgets.logger
msl.qt.widgets.notes_history
msl.qt.widgets.comments
msl.qt.widgets.spinboxes
msl.qt.widgets.toggle_switch
2 changes: 1 addition & 1 deletion msl/examples/qt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
from . import logger
from . import toggle_switch
from . import button
from . import notes_history
from . import comments
from .loop_until_abort_sleep import LoopExampleSleep
from . import led
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
A :func:`~msl.qt.prompt.notes` example.
A :func:`~msl.qt.prompt.comments` example.
"""
import os
import json
Expand All @@ -19,16 +19,16 @@
def show():
dummy = [
{'timestamp': (datetime.datetime.now() + datetime.timedelta(days=i)).strftime('%Y-%m-%d %H:%M:%S'),
'notes': 'The {} {} {} {} {} the {}'.format(
'comment': 'The {} {} {} {} {} the {}'.format(
*map(random.choice, (adjectives, nouns, verbs, adverbs, prepositions, nouns)))}
for i in range(1000)
]

dummy_file = os.path.join(tempfile.gettempdir(), 'msl-qt-notes-history-example.json')
dummy_file = os.path.join(tempfile.gettempdir(), 'msl-qt-comments-example.json')
with open(dummy_file, 'w') as fp:
json.dump(dummy, fp, indent=2, ensure_ascii=False)

print('The note entered is:\n' + qt.prompt.notes(path=dummy_file))
print('The comment entered is:\n' + qt.prompt.comments(path=dummy_file))
os.remove(dummy_file)


Expand Down
49 changes: 24 additions & 25 deletions msl/qt/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,50 +232,49 @@ def item(message, items, *, title=None, font=None, index=0):
return items[items_.index(dialog.textValue())] if ok else None


def notes(*, path=None, title=None, even_row_color='#FFFFFF', odd_row_color='#EAF2F8'):
"""Ask the user to enter notes.
Opens a :class:`QtWidgets.QDialog` to allow for a user to enter a detailed
description of a task that they are performing. The :class:`QtWidgets.QDialog`
provides a table of all the previous notes that have been used. Notes that are
in the table can be deleted by selecting the desired row(s) and pressing the
``delete`` key or the note in a row can be copied to the note editor by
double-clicking on a row.
This function is useful when acquiring data and you want to include notes
about how the data was acquired. Using a prompt to enter notes forces you
to manually enter the notes every time you acquire data rather than having
the notes typed directly onto the graphical user interface, which you might
forget to update before acquiring the next data set.
def comments(*, path=None, title=None, even_row_color='#FFFFFF', odd_row_color='#EAF2F8'):
"""Ask the user to enter comments.
Opens a :class:`QtWidgets.QDialog` to allow for a user to enter comments about
a task that they are performing. The dialog provides a table of all the previous
comments that have been used. Comments that are in the table can be deleted by
selecting the desired row(s) and pressing the ``Delete`` key or the comment in
a row can be selected by double-clicking on a row.
This function is useful when acquiring data and you want to include comments
about how the data was acquired. Using a prompt to enter comments forces you
to enter a new comment (or use a previous comment) every time you acquire data
rather than having the comments in a, for example :class:`QtWidgets.QPlainTextEdit`,
which you might forget to update before acquiring the next data set.
.. _JSON: https://www.json.org/
Parameters
----------
path : :class:`str`, optional
The path to a JSON_ file that contains the history of the notes that have
The path to a JSON_ file that contains the history of the comments that have
been used. If :data:`None` then the default file is used. The file will
automatically be created if it does not exist.
title : :class:`str`, optional
The text to display in the title bar of the dialog window.
even_row_color : :class:`QtGui.QColor`, optional
even_row_color
The background color of the even-numbered rows in the history table.
Can be any data type and value that the constructor of a
:class:`QtGui.QColor` accepts.
odd_row_color : :class:`QtGui.QColor`, optional
See :func:`~msl.qt.utils.to_qcolor` for details about the different
data types that are supported.
odd_row_color
The background color of the odd-numbered rows in the history table.
Can be any data type and value that the constructor of a
:class:`QtGui.QColor` accepts.
See :func:`~msl.qt.utils.to_qcolor` for details about the different
data types that are supported.
Returns
-------
:class:`str`
The note that was entered.
The comment that was entered.
"""
# import here since there are circular import errors if you import at the module level
from .widgets.notes_history import NotesHistory
from .widgets.comments import Comments
app, title = _get_app_and_title(title)
nh = NotesHistory(app.activeWindow(), path, title, even_row_color, odd_row_color)
nh = Comments(path, title, even_row_color, odd_row_color)
nh.exec_()
return nh.text()

Expand Down
78 changes: 39 additions & 39 deletions msl/qt/widgets/notes_history.py → msl/qt/widgets/comments.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,58 @@
"""
A :class:`QtWidgets.QDialog` to prompt the user to enter notes.
A :class:`QtWidgets.QDialog` to prompt the user to enter comments.
"""
import os
import json
from datetime import datetime

from .. import (
application,
QtWidgets,
Qt,
QtGui,
prompt,
Button,
utils,
)
from ..constants import HOME_DIR


class NotesHistory(QtWidgets.QDialog):
class Comments(QtWidgets.QDialog):

def __init__(self, parent, json_path, title, even_row_color, odd_row_color):
"""Do not instantiate directly. Use :func:`msl.qt.prompt.notes` instead."""
super(NotesHistory, self).__init__(parent=parent)
def __init__(self, json_path, title, even_row_color, odd_row_color):
"""A :class:`QtWidgets.QDialog` to prompt the user to enter comments.
self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinMaxButtonsHint)
Do not instantiate directly. Use :func:`msl.qt.prompt.comments` instead.
"""
super(Comments, self).__init__(None, Qt.WindowCloseButtonHint | Qt.WindowMinMaxButtonsHint)
self.setWindowTitle(title)

self.path = json_path if json_path else os.path.join(HOME_DIR, 'qt-notes-history.json')
self.path = json_path if json_path else os.path.join(HOME_DIR, 'msl-qt-comments.json')

self.notes = []
self.even_row_color = QtGui.QColor(even_row_color)
self.odd_row_color = QtGui.QColor(odd_row_color)
self.comments = []
self.even_row_color = utils.to_qcolor(even_row_color)
self.odd_row_color = utils.to_qcolor(odd_row_color)

self.load_json()
self.create_widgets()

geo = application().desktop().availableGeometry()
geo = utils.screen_geometry(widget=self)
self.resize(int(geo.width()*0.4), int(geo.height()*0.6))

def append_to_history_table(self, timestamp, note):
def append_to_history_table(self, timestamp, comment):
index = self.table.rowCount()
self.table.insertRow(index)
self.table.setItem(index, 0, QtWidgets.QTableWidgetItem(timestamp))
self.table.setItem(index, 1, QtWidgets.QTableWidgetItem(note))
self.table.setItem(index, 1, QtWidgets.QTableWidgetItem(comment))

def apply_filter(self):
filter_text = self.filter_edit.text().lower()
if not filter_text and self.table.rowCount() == len(self.notes):
if not filter_text and self.table.rowCount() == len(self.comments):
# all rows are already visible
return

self.table.setRowCount(0)
for item in self.notes:
if not filter_text or filter_text in item['timestamp'] or filter_text in item['notes'].lower():
self.append_to_history_table(item['timestamp'], item['notes'])
for item in self.comments:
if not filter_text or filter_text in item['timestamp'] or filter_text in item['comment'].lower():
self.append_to_history_table(item['timestamp'], item['comment'])
self.update_table_row_colors_and_resize()

def clear_filter(self):
Expand All @@ -62,28 +62,28 @@ def clear_filter(self):
self.apply_filter()

def clear_history(self):
if not self.notes or not prompt.yes_no('Clear the entire history?', default=False):
if not self.comments or not prompt.yes_no('Clear the entire history?', default=False):
return
self.table.setRowCount(0)
self.notes = []
self.comments = []
self.save_json()

def create_widgets(self):
self.note_edit = QtWidgets.QPlainTextEdit(self)
height = self.note_edit.fontMetrics().lineSpacing()
self.note_edit.setFixedHeight(5 * height) # display 5 lines
self.comment_textedit = QtWidgets.QPlainTextEdit(self)
height = self.comment_textedit.fontMetrics().lineSpacing()
self.comment_textedit.setFixedHeight(5 * height) # display 5 lines

self.ok_button = Button(
text='OK',
left_click=self.prepend_and_close,
tooltip='Select the note and exit',
tooltip='Select the comment and exit',
parent=self,
)
self.ok_button.add_menu_item(
text='Clear history',
icon=QtWidgets.QStyle.SP_DialogResetButton,
triggered=self.clear_history,
tooltip='Delete all notes that are in the history'
tooltip='Delete all comments that are in the history'
)

#
Expand Down Expand Up @@ -114,7 +114,7 @@ def create_widgets(self):
# history table
#
self.table = QtWidgets.QTableWidget()
table_header = ['Timestamp', 'Notes']
table_header = ['Timestamp', 'Comment']
self.table.setColumnCount(len(table_header))
self.table.setHorizontalHeaderLabels(table_header)
self.table.setSortingEnabled(True)
Expand All @@ -124,16 +124,16 @@ def create_widgets(self):
self.table.horizontalHeader().sectionClicked.connect(self.update_table_row_colors_and_resize)
self.table.cellDoubleClicked.connect(self.table_double_click)
self.table.keyPressEvent = self.table_key_press
for item in self.notes:
self.append_to_history_table(item['timestamp'], item['notes'])
for item in self.comments:
self.append_to_history_table(item['timestamp'], item['comment'])
self.update_table_row_colors_and_resize()

#
# main layout
#
layout = QtWidgets.QVBoxLayout()
layout.addWidget(QtWidgets.QLabel('Enter a new note or select one from the history below'))
layout.addWidget(self.note_edit)
layout.addWidget(QtWidgets.QLabel('Enter a new comment or select one from the history below'))
layout.addWidget(self.comment_textedit)
layout.addWidget(self.ok_button)
layout.addLayout(filter_layout)
layout.addWidget(self.table)
Expand All @@ -146,19 +146,19 @@ def load_json(self):

with open(self.path, 'rb') as fp:
try:
self.notes = json.load(fp, encoding='utf-8')
self.comments = json.load(fp, encoding='utf-8')
except Exception as e:
prompt.warning('Error loading JSON file:\n{}\n\n{}'.format(self.path, e))

def prepend_and_close(self):
self.close()

if not self.text():
# no new notes were entered so there is nothing to save to the history file
# no new comments were entered so there is nothing to save to the history file
return

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.notes.insert(0, {'timestamp': timestamp, 'notes': self.text()})
self.comments.insert(0, {'timestamp': timestamp, 'comments': self.text()})
self.save_json()

def save_json(self):
Expand All @@ -168,10 +168,10 @@ def save_json(self):
os.makedirs(root)

with open(self.path, 'w') as fp:
json.dump(self.notes, fp, indent=2, ensure_ascii=False)
json.dump(self.comments, fp, indent=2, ensure_ascii=False)

def table_double_click(self, row, col):
self.note_edit.setPlainText(self.table.item(row, 1).text())
self.comment_textedit.setPlainText(self.table.item(row, 1).text())

def table_key_press(self, event):
# CTRL+A pressed
Expand All @@ -195,13 +195,13 @@ def table_key_press(self, event):

for index in selected:
self.table.removeRow(index)
del self.notes[index]
del self.comments[index]

self.save_json()

def text(self):
"""str: The text in the note editor"""
return self.note_edit.toPlainText().strip()
"""str: The text in the comment editor"""
return self.comment_textedit.toPlainText().strip()

def update_table_row_colors_and_resize(self):
for row in range(self.table.rowCount()):
Expand Down
2 changes: 1 addition & 1 deletion tests/iterate_through_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

examples = [
example.loop_until_abort_sleep.main,
example.notes_history.show,
example.comments.show,
example.button.show,
example.logger.show,
example.toggle_switch.show,
Expand Down

0 comments on commit 6e78a69

Please sign in to comment.