app_Main.py 484 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from appCommon.Common import LoudDict
  39. from appCommon.Common import color_variant
  40. from appCommon.Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray, FCInputDialogSlider
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. # version = "Unstable Version"
  138. version = 8.994
  139. version_date = "2020/11/7"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal([str], [str, bool])
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, qapp, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. log.info("FlatCAM Starting...")
  222. self.qapp = qapp
  223. # App Editors will be instantiated further below
  224. self.exc_editor = None
  225. self.grb_editor = None
  226. self.geo_editor = None
  227. # ############################################################################################################
  228. # ################# Setup the listening thread for another instance launching with args ######################
  229. # ############################################################################################################
  230. if sys.platform == 'win32' or sys.platform == 'linux':
  231. # make sure the thread is stored by using a self. otherwise it's garbage collected
  232. self.listen_th = QtCore.QThread()
  233. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  234. self.new_launch = ArgsThread()
  235. self.new_launch.open_signal[list].connect(self.on_startup_args)
  236. self.new_launch.moveToThread(self.listen_th)
  237. self.new_launch.start.emit()
  238. # ############################################################################################################
  239. # ########################################## OS-specific #####################################################
  240. # ############################################################################################################
  241. portable = False
  242. # Folder for user settings.
  243. if sys.platform == 'win32':
  244. if platform.architecture()[0] == '32bit':
  245. self.log.debug("Win32!")
  246. else:
  247. self.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. self.log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. self.log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. self.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. self.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = self.preprocessors_path()
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. self.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create tools_db.FlatDB file if there is none
  299. db_path = self.tools_database_path()
  300. try:
  301. f = open(db_path)
  302. f.close()
  303. except IOError:
  304. self.log.debug('Creating empty tools_db.FlatDB')
  305. f = open(db_path, 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # create current_defaults.FlatConfig file if there is none
  309. def_path = self.defaults_path()
  310. try:
  311. f = open(def_path)
  312. f.close()
  313. except IOError:
  314. self.log.debug('Creating empty current_defaults.FlatConfig')
  315. f = open(def_path, 'w')
  316. json.dump({}, f)
  317. f.close()
  318. # the factory defaults are written only once at the first launch of the application after installation
  319. FlatCAMDefaults.save_factory_defaults(self.factory_defaults_path(), self.version)
  320. # create a recent files json file if there is none
  321. rec_f_path = self.recent_files_path()
  322. try:
  323. f = open(rec_f_path)
  324. f.close()
  325. except IOError:
  326. self.log.debug('Creating empty recent.json')
  327. f = open(rec_f_path, 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. rec_proj_path = self.recent_projects_path()
  332. try:
  333. fp = open(rec_proj_path)
  334. fp.close()
  335. except IOError:
  336. self.log.debug('Creating empty recent_projects.json')
  337. fp = open(rec_proj_path, 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. self.log.debug("Application path is " + self.app_home)
  344. self.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  353. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  354. if user_defaults:
  355. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  356. if self.defaults['units'] == 'MM':
  357. self.decimals = int(self.defaults['decimals_metric'])
  358. else:
  359. self.decimals = int(self.defaults['decimals_inch'])
  360. if self.defaults["global_gray_icons"] is False:
  361. self.resource_location = 'assets/resources'
  362. else:
  363. self.resource_location = 'assets/resources/dark_resources'
  364. self.current_units = self.defaults['units']
  365. # ###########################################################################################################
  366. # #################################### SETUP OBJECT CLASSES #################################################
  367. # ###########################################################################################################
  368. self.setup_obj_classes()
  369. # ###########################################################################################################
  370. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  371. # ###########################################################################################################
  372. self.pool = Pool()
  373. # ###########################################################################################################
  374. # ###################################### Clear GUI Settings - once at first start ###########################
  375. # ###########################################################################################################
  376. if self.defaults["first_run"] is True:
  377. # on first run clear the previous QSettings, therefore clearing the GUI settings
  378. qsettings = QSettings("Open Source", "FlatCAM")
  379. for key in qsettings.allKeys():
  380. qsettings.remove(key)
  381. # This will write the setting to the platform specific storage.
  382. del qsettings
  383. # ###########################################################################################################
  384. # ###################################### Setting the Splash Screen ##########################################
  385. # ###########################################################################################################
  386. splash_settings = QSettings("Open Source", "FlatCAM")
  387. if splash_settings.contains("splash_screen"):
  388. show_splash = splash_settings.value("splash_screen")
  389. else:
  390. splash_settings.setValue('splash_screen', 1)
  391. # This will write the setting to the platform specific storage.
  392. del splash_settings
  393. show_splash = 1
  394. if show_splash and self.cmd_line_headless != 1:
  395. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  396. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  397. # self.splash.setMask(splash_pix.mask())
  398. # move splashscreen to the current monitor
  399. desktop = QtWidgets.QApplication.desktop()
  400. screen = desktop.screenNumber(QtGui.QCursor.pos())
  401. current_screen_center = desktop.availableGeometry(screen).center()
  402. self.splash.move(current_screen_center - self.splash.rect().center())
  403. self.splash.show()
  404. self.splash.showMessage(_("The application is initializing ..."),
  405. alignment=Qt.AlignBottom | Qt.AlignLeft,
  406. color=QtGui.QColor("gray"))
  407. else:
  408. self.splash = None
  409. show_splash = 0
  410. # ###########################################################################################################
  411. # ######################################### Initialize GUI ##################################################
  412. # ###########################################################################################################
  413. # FlatCAM colors used in plotting
  414. self.FC_light_green = '#BBF268BF'
  415. self.FC_dark_green = '#006E20BF'
  416. self.FC_light_blue = '#a5a5ffbf'
  417. self.FC_dark_blue = '#0000ffbf'
  418. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  419. if theme_settings.contains("theme"):
  420. theme = theme_settings.value('theme', type=str)
  421. else:
  422. theme = 'white'
  423. if self.defaults["global_cursor_color_enabled"]:
  424. self.cursor_color_3D = self.defaults["global_cursor_color"]
  425. else:
  426. if theme == 'white':
  427. self.cursor_color_3D = 'black'
  428. else:
  429. self.cursor_color_3D = 'gray'
  430. # update the defaults dict with the setting in QSetting
  431. self.defaults['global_theme'] = theme
  432. self.ui = MainGUI(self)
  433. # set FlatCAM units in the Status bar
  434. self.set_screen_units(self.defaults['units'])
  435. # ###########################################################################################################
  436. # ########################################### AUTOSAVE SETUP ################################################
  437. # ###########################################################################################################
  438. self.block_autosave = False
  439. self.autosave_timer = QtCore.QTimer(self)
  440. self.save_project_auto_update()
  441. self.autosave_timer.timeout.connect(self.save_project_auto)
  442. # ###########################################################################################################
  443. # #################################### LOAD PREPROCESSORS ###################################################
  444. # ###########################################################################################################
  445. # ----------------------------------------- WARNING --------------------------------------------------------
  446. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  447. # That's because the number of preprocessors can vary and here the comboboxes are populated
  448. # -----------------------------------------------------------------------------------------------------------
  449. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  450. # the preprocessor file
  451. self.preprocessors = load_preprocessors(self)
  452. # make sure that always the 'default' preprocessor is the first item in the dictionary
  453. if 'default' in self.preprocessors.keys():
  454. new_ppp_dict = {}
  455. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  456. default_pp = self.preprocessors.pop('default')
  457. new_ppp_dict['default'] = default_pp
  458. # then add the rest of the keys
  459. for name, val_class in self.preprocessors.items():
  460. new_ppp_dict[name] = val_class
  461. # and now put back the ordered dict with 'default' key first
  462. self.preprocessors = new_ppp_dict
  463. # populate the Preprocessor ComboBoxes in the PREFERENCES
  464. for name in list(self.preprocessors.keys()):
  465. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  466. if name.partition('_')[0] == 'Paste':
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  468. continue
  469. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  470. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  471. if name == 'hpgl':
  472. continue
  473. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  474. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  475. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  476. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  477. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  478. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  479. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  480. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  481. QtCore.Qt.ToolTipRole)
  482. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  483. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  484. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  485. QtCore.Qt.ToolTipRole)
  486. # ###########################################################################################################
  487. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  488. # ###########################################################################################################
  489. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  490. inform=self.inform)
  491. self.preferencesUiManager.defaults_write_form()
  492. # When the self.defaults dictionary changes will update the Preferences GUI forms
  493. self.defaults.set_change_callback(self.on_defaults_dict_change)
  494. # ###########################################################################################################
  495. # ############################################ Data #########################################################
  496. # ###########################################################################################################
  497. self.recent = []
  498. self.recent_projects = []
  499. self.clipboard = QtWidgets.QApplication.clipboard()
  500. self.project_filename = None
  501. self.toggle_units_ignore = False
  502. self.main_thread = QtWidgets.QApplication.instance().thread()
  503. # ###########################################################################################################
  504. # ########################################## LOAD LANGUAGES ################################################
  505. # ###########################################################################################################
  506. self.languages = fcTranslate.load_languages()
  507. for name in sorted(self.languages.values()):
  508. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  509. # ###########################################################################################################
  510. # ####################################### APPLY APP LANGUAGE ################################################
  511. # ###########################################################################################################
  512. ret_val = fcTranslate.apply_language('strings')
  513. if ret_val == "no language":
  514. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  515. self.log.debug("Could not find the Language files. The App strings are missing.")
  516. else:
  517. # make the current language the current selection on the language combobox
  518. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  519. self.log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  520. # ###########################################################################################################
  521. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  522. # ###########################################################################################################
  523. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  524. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  525. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  526. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  527. self.defaults.propagate_defaults()
  528. # ###########################################################################################################
  529. # ######################################## UPDATE THE OPTIONS ###############################################
  530. # ###########################################################################################################
  531. self.options = LoudDict()
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Update the self.options from the self.defaults
  534. # The self.defaults holds the application defaults while the self.options holds the object defaults
  535. # -----------------------------------------------------------------------------------------------------------
  536. # Copy app defaults to project options
  537. for def_key, def_val in self.defaults.items():
  538. self.options[def_key] = deepcopy(def_val)
  539. self.preferencesUiManager.show_preferences_gui()
  540. # ### End of Data ####
  541. # ###########################################################################################################
  542. # #################################### SETUP OBJECT COLLECTION ##############################################
  543. # ###########################################################################################################
  544. self.collection = ObjectCollection(app=self)
  545. self.ui.project_tab_layout.addWidget(self.collection.view)
  546. self.app_obj = AppObject(app=self)
  547. # ### Adjust tabs width ## ##
  548. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  549. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  550. self.collection.view.setMinimumWidth(290)
  551. self.log.debug("Finished creating Object Collection.")
  552. # ###########################################################################################################
  553. # ######################################## SETUP Plot Area ##################################################
  554. # ###########################################################################################################
  555. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  556. if self.defaults["global_graphic_engine"] == '3D':
  557. self.is_legacy = False
  558. else:
  559. self.is_legacy = True
  560. # Event signals disconnect id holders
  561. self.mp = None
  562. self.mm = None
  563. self.mr = None
  564. self.mdc = None
  565. self.mp_zc = None
  566. self.kp = None
  567. # Matplotlib axis
  568. self.axes = None
  569. if show_splash:
  570. self.splash.showMessage(_("The application is initializing ...\n"
  571. "Canvas initialization started."),
  572. alignment=Qt.AlignBottom | Qt.AlignLeft,
  573. color=QtGui.QColor("gray"))
  574. start_plot_time = time.time() # debug
  575. self.plotcanvas = None
  576. self.app_cursor = None
  577. self.hover_shapes = None
  578. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  579. # setup the PlotCanvas
  580. self.on_plotcanvas_setup()
  581. end_plot_time = time.time()
  582. self.used_time = end_plot_time - start_plot_time
  583. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  584. if show_splash:
  585. self.splash.showMessage('%s: %ssec' % (_("The application is initializing ...\n"
  586. "Canvas initialization started.\n"
  587. "Canvas initialization finished in"), '%.2f' % self.used_time),
  588. alignment=Qt.AlignBottom | Qt.AlignLeft,
  589. color=QtGui.QColor("gray"))
  590. self.ui.splitter.setStretchFactor(1, 2)
  591. # ###########################################################################################################
  592. # ############################################### Worker SETUP ##############################################
  593. # ###########################################################################################################
  594. if self.defaults["global_worker_number"]:
  595. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  596. else:
  597. self.workers = WorkerStack(workers_number=2)
  598. self.worker_task.connect(self.workers.add_task)
  599. self.log.debug("Finished creating Workers crew.")
  600. # ###########################################################################################################
  601. # ############################################# Activity Monitor ############################################
  602. # ###########################################################################################################
  603. # self.activity_view = FlatCAMActivityView(app=self)
  604. # self.ui.infobar.addWidget(self.activity_view)
  605. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  606. # ###########################################################################################################
  607. # ########################################## Other setups ###################################################
  608. # ###########################################################################################################
  609. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  610. # depending on from where those tools are called different actions can be done
  611. self.call_source = 'app'
  612. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  613. self.tool_tab_locked = False
  614. # decide if to show or hide the Notebook side of the screen at startup
  615. if self.defaults["global_project_at_startup"] is True:
  616. self.ui.splitter.setSizes([1, 1])
  617. else:
  618. self.ui.splitter.setSizes([0, 1])
  619. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  620. self.setup_default_properties_tab()
  621. # ###########################################################################################################
  622. # ####################################### Auto-complete KEYWORDS ############################################
  623. # ###########################################################################################################
  624. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  625. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  626. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  627. 'export_exc',
  628. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  629. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  630. 'interiors', 'isolate', 'join_excellon',
  631. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  632. 'mirror', 'ncc',
  633. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  634. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  635. 'options', 'origin',
  636. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  637. 'save', 'save_project',
  638. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  639. 'skew', 'subtract_poly', 'subtract_rectangle',
  640. 'version', 'write_gcode'
  641. ]
  642. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  643. 'Paste_1',
  644. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  645. 'Toolchange_manual', 'True', 'Users',
  646. 'all', 'auto', 'axis',
  647. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  648. 'contour', 'default',
  649. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  650. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  651. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  652. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  653. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  654. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  655. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  656. 'spacing_columns',
  657. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  658. 'toolchange_xy', 'toolchangez', 'travelz',
  659. 'tooldia', 'use_threads', 'value',
  660. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  661. ]
  662. self.tcl_keywords = [
  663. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  664. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  665. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  666. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  667. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  668. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  669. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  670. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  671. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  672. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  673. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  674. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  675. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  676. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  677. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  678. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  679. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  680. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  681. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  682. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  683. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  684. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  685. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  686. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  687. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  688. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  689. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  690. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  691. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  692. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  693. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  694. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  695. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  696. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  697. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  698. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  699. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  700. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  701. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  702. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  703. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  704. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  705. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  706. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  707. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  708. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  709. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  710. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  711. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  712. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  713. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  714. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  715. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  716. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  717. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  718. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  719. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  720. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  721. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  722. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  723. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  724. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  725. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  726. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  727. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  728. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  729. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  730. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  731. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  732. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  733. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  734. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  735. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  736. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  737. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  738. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  739. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  740. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  741. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  742. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  743. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  744. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  745. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  746. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  747. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  748. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  749. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  750. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  751. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  752. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  753. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  754. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  755. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  756. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  757. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  758. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  759. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  760. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  761. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  762. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  763. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  764. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  765. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  766. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  767. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  768. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  769. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  770. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  771. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  772. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  773. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  774. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  775. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  776. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  777. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  778. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  779. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  780. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  781. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  782. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  783. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  784. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  785. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  786. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  787. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  788. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  789. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  790. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  791. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  792. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  793. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  794. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  795. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  796. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  797. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  798. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  799. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  800. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  801. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  802. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  803. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  804. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  805. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  806. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  807. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  808. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  809. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  810. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  811. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  812. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  813. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  814. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  815. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  816. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  817. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  818. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  819. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  820. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  821. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  822. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  823. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  824. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  825. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  826. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  827. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  828. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  829. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  830. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  831. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  832. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  833. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  834. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  835. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  836. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  837. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  838. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  839. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  840. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  841. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  842. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  843. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  844. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  845. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  846. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  847. ]
  848. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  849. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  850. # ###########################################################################################################
  851. # ########################################## Tools and Plugins ##############################################
  852. # ###########################################################################################################
  853. self.shell = None
  854. self.dblsidedtool = None
  855. self.distance_tool = None
  856. self.distance_min_tool = None
  857. self.panelize_tool = None
  858. self.film_tool = None
  859. self.paste_tool = None
  860. self.calculator_tool = None
  861. self.rules_tool = None
  862. self.sub_tool = None
  863. self.move_tool = None
  864. self.cutout_tool = None
  865. self.ncclear_tool = None
  866. self.paint_tool = None
  867. self.isolation_tool = None
  868. self.drilling_tool = None
  869. self.optimal_tool = None
  870. self.transform_tool = None
  871. self.properties_tool = None
  872. self.pdf_tool = None
  873. self.image_tool = None
  874. self.pcb_wizard_tool = None
  875. self.cal_exc_tool = None
  876. self.qrcode_tool = None
  877. self.copper_thieving_tool = None
  878. self.fiducial_tool = None
  879. self.edrills_tool = None
  880. self.align_objects_tool = None
  881. self.punch_tool = None
  882. self.invert_tool = None
  883. self.corners_tool = None
  884. self.etch_tool = None
  885. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  886. try:
  887. self.install_tools()
  888. except AttributeError as e:
  889. self.log.debug("App.__init__() install_tools() --> %s" % str(e))
  890. # ###########################################################################################################
  891. # ######################################### BookMarks Manager ###############################################
  892. # ###########################################################################################################
  893. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  894. self.install_bookmarks()
  895. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  896. # ###########################################################################################################
  897. # ########################################### Tools Database ################################################
  898. # ###########################################################################################################
  899. self.tools_db_tab = None
  900. # ### System Font Parsing ###
  901. # self.f_parse = ParseFont(self)
  902. # self.parse_system_fonts()
  903. # ###########################################################################################################
  904. # ############################################## Shell SETUP ################################################
  905. # ###########################################################################################################
  906. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  907. if self.defaults["global_shell_at_startup"]:
  908. self.ui.shell_dock.show()
  909. else:
  910. self.ui.shell_dock.hide()
  911. # ###########################################################################################################
  912. # ######################################### Check for updates ###############################################
  913. # ###########################################################################################################
  914. # Separate thread (Not worker)
  915. # Check for updates on startup but only if the user consent and the app is not in Beta version
  916. if (self.beta is False or self.beta is None) and \
  917. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  918. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  919. # self.thr2 = QtCore.QThread()
  920. self.worker_task.emit({'fcn': self.version_check,
  921. 'params': []})
  922. # self.thr2.start(QtCore.QThread.LowPriority)
  923. # ###########################################################################################################
  924. # ##################################### Register files with FlatCAM; #######################################
  925. # ################################### It works only for Windows for now ####################################
  926. # ###########################################################################################################
  927. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  928. self.on_register_files()
  929. # ###########################################################################################################
  930. # ######################################## Variables for global usage #######################################
  931. # ###########################################################################################################
  932. # hold the App units
  933. self.units = 'MM'
  934. # coordinates for relative position display
  935. self.rel_point1 = (0, 0)
  936. self.rel_point2 = (0, 0)
  937. # variable to store coordinates
  938. self.pos = (0, 0)
  939. self.pos_canvas = (0, 0)
  940. self.pos_jump = (0, 0)
  941. # variable to store mouse coordinates
  942. self.mouse = [0, 0]
  943. # variable to store the delta positions on cavnas
  944. self.dx = 0
  945. self.dy = 0
  946. # decide if we have a double click or single click
  947. self.doubleclick = False
  948. # store here the is_dragging value
  949. self.event_is_dragging = False
  950. # variable to store if a command is active (then the var is not None) and which one it is
  951. self.command_active = None
  952. # variable to store the status of moving selection action
  953. # None value means that it's not an selection action
  954. # True value = a selection from left to right
  955. # False value = a selection from right to left
  956. self.selection_type = None
  957. # List to store the objects that are currently loaded in FlatCAM
  958. # This list is updated on each object creation or object delete
  959. self.all_objects_list = []
  960. self.objects_under_the_click_list = []
  961. # List to store the objects that are selected
  962. self.sel_objects_list = []
  963. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  964. self.key_modifiers = None
  965. # Variable to store the status of the code editor
  966. self.toggle_codeeditor = False
  967. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  968. self.click_noproject = False
  969. self.cursor = None
  970. # Variable to store the GCODE that was edited
  971. self.gcode_edited = ""
  972. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  973. self.old_state_of_tools_toolbar = False
  974. self.text_editor_tab = None
  975. # here store the color of a Tab text before it is changed so it can be restored in the future
  976. self.old_tab_text_color = None
  977. # reference for the self.ui.code_editor
  978. self.reference_code_editor = None
  979. self.script_code = ''
  980. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  981. self.tools_db_changed_flag = False
  982. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  983. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  984. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  985. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  986. 'tsm']
  987. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  988. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  989. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  990. 'sbp', 'tap', 'xpi']
  991. self.svg_list = ['svg']
  992. self.dxf_list = ['dxf']
  993. self.pdf_list = ['pdf']
  994. self.prj_list = ['flatprj']
  995. self.conf_list = ['flatconfig']
  996. # last used filters
  997. self.last_op_gerber_filter = None
  998. self.last_op_excellon_filter = None
  999. self.last_op_gcode_filter = None
  1000. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1001. # flag for polygons not cleared
  1002. self.poly_not_cleared = False
  1003. # VisPy visuals
  1004. self.isHovering = False
  1005. self.notHovering = True
  1006. # Window geometry
  1007. self.x_pos = None
  1008. self.y_pos = None
  1009. self.width = None
  1010. self.height = None
  1011. # when True, the app has to return from any thread
  1012. self.abort_flag = False
  1013. # set the value used in the Windows Title
  1014. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1015. # this holds a widget that is installed in the Plot Area when View Source option is used
  1016. self.source_editor_tab = None
  1017. self.pagesize = {}
  1018. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1019. # VisPy visuals
  1020. if self.is_legacy is False:
  1021. try:
  1022. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1023. except AttributeError:
  1024. self.tool_shapes = None
  1025. else:
  1026. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1027. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1028. # used in the delayed shutdown self.start_delayed_quit() method
  1029. self.save_timer = None
  1030. # ###########################################################################################################
  1031. # ################################## ADDING FlatCAM EDITORS section #########################################
  1032. # ###########################################################################################################
  1033. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1034. # at the first launch of the App , the editors will not be functional.
  1035. try:
  1036. self.geo_editor = AppGeoEditor(self)
  1037. except Exception as es:
  1038. self.log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1039. try:
  1040. self.exc_editor = AppExcEditor(self)
  1041. except Exception as es:
  1042. self.log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1043. try:
  1044. self.grb_editor = AppGerberEditor(self)
  1045. except Exception as es:
  1046. self.log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1047. try:
  1048. self.gcode_editor = AppGCodeEditor(self)
  1049. except Exception as es:
  1050. self.log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1051. self.log.debug("Finished adding FlatCAM Editor's.")
  1052. self.ui.set_ui_title(name=_("New Project - Not saved"))
  1053. # ###########################################################################################################
  1054. # ########################################## Install OPTIMIZATIONS for GCode generation #####################
  1055. # ###########################################################################################################
  1056. current_platform = platform.architecture()[0]
  1057. if current_platform != '64bit':
  1058. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1059. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1060. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1061. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1062. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1063. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1064. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1065. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1066. # ###########################################################################################################
  1067. # ########################################### EXCLUSION AREAS ###############################################
  1068. # ###########################################################################################################
  1069. self.exc_areas = ExclusionAreas(app=self)
  1070. # ###########################################################################################################
  1071. # ###########################################################################################################
  1072. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1073. # ###########################################################################################################
  1074. # ###########################################################################################################
  1075. self.f_handlers = MenuFileHandlers(app=self)
  1076. # this is calculated in the class above (somehow?)
  1077. self.defaults["root_folder_path"] = self.app_home
  1078. # ###########################################################################################################
  1079. # ##################################### FIRST RUN SECTION ###################################################
  1080. # ################################ It's done only once after install #####################################
  1081. # ###########################################################################################################
  1082. if self.defaults["first_run"] is True:
  1083. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  1084. self.log.debug("-> First Run: Setting up the first Layout")
  1085. initial_lay = 'minimal'
  1086. self.on_layout(lay=initial_lay)
  1087. # Set the combobox in Preferences to the current layout
  1088. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  1089. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  1090. # after the first run, this object should be False
  1091. self.defaults["first_run"] = False
  1092. self.log.debug("-> First Run: Updating the Defaults file with Factory Defaults")
  1093. self.preferencesUiManager.save_defaults(silent=True)
  1094. # ###########################################################################################################
  1095. # ############################################### SYS TRAY ##################################################
  1096. # ###########################################################################################################
  1097. if self.defaults["global_systray_icon"]:
  1098. self.parent_w = QtWidgets.QWidget()
  1099. if self.cmd_line_headless == 1:
  1100. self.trayIcon = FlatCAMSystemTray(app=self,
  1101. icon=QtGui.QIcon(self.resource_location +
  1102. '/flatcam_icon32_green.png'),
  1103. headless=True,
  1104. parent=self.parent_w)
  1105. else:
  1106. self.trayIcon = FlatCAMSystemTray(app=self,
  1107. icon=QtGui.QIcon(self.resource_location +
  1108. '/flatcam_icon32_green.png'),
  1109. parent=self.parent_w)
  1110. # ###########################################################################################################
  1111. # ############################################ SETUP RECENT ITEMS ###########################################
  1112. # ###########################################################################################################
  1113. self.setup_recent_items()
  1114. # ###########################################################################################################
  1115. # ###########################################################################################################
  1116. # ############################################# Signal handling #############################################
  1117. # ###########################################################################################################
  1118. # ###########################################################################################################
  1119. # ########################################## Custom signals ################################################
  1120. # signal for displaying messages in status bar
  1121. self.inform[str].connect(self.info)
  1122. self.inform[str, bool].connect(self.info)
  1123. # signal for displaying messages in the shell
  1124. self.inform_shell[str].connect(self.info_shell)
  1125. self.inform_shell[str, bool].connect(self.info_shell)
  1126. # signal to be called when the app is quiting
  1127. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1128. self.message.connect(lambda: message_dialog(parent=self.ui))
  1129. # self.progress.connect(self.set_progress_bar)
  1130. # signals emitted when file state change
  1131. self.file_opened.connect(self.register_recent)
  1132. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1133. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1134. # when the defaults dictionary values change
  1135. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1136. # ########################################## Standard signals ###############################################
  1137. # ### Menu
  1138. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1139. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1140. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1141. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1142. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1143. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1144. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1145. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1146. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1147. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1148. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1149. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1150. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1151. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1152. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1153. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1154. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1155. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1156. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1157. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1158. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1159. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1160. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1161. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1162. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1163. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1164. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1165. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1166. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1167. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1168. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1169. self.ui.menufile_exit.triggered.connect(self.final_save)
  1170. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1171. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1172. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1173. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1174. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1175. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1176. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1177. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1178. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1179. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1180. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1181. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1182. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1183. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1184. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1185. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1186. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1187. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1188. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1189. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1190. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1191. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1192. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1193. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1194. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1195. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1196. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1197. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1198. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1199. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1200. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1201. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1202. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1203. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1204. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1205. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1206. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1207. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1208. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1209. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1210. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1211. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1212. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1213. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1214. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1215. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1216. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1217. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1218. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1219. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1220. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1221. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1222. self.ui.menuhelp_readme.triggered.connect(self.on_howto)
  1223. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1224. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1225. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1226. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1227. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1228. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1229. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1230. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1231. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1232. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1233. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1234. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1235. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1236. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1237. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1238. # ToolBar signals
  1239. self.connect_toolbar_signals()
  1240. # Context Menu
  1241. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1242. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1243. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1244. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1245. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1246. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1247. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1248. self.ui.clearplot.triggered.connect(self.clear_plots)
  1249. self.ui.replot.triggered.connect(self.plot_all)
  1250. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1251. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1252. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1253. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1254. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1255. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1256. # Project Context Menu -> Color Setting
  1257. for act in self.ui.menuprojectcolor.actions():
  1258. act.triggered.connect(self.on_set_color_action_triggered)
  1259. # Notebook tab clicking
  1260. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1261. # ###########################################################################################################
  1262. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1263. # ###########################################################################################################
  1264. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1265. lambda: self.on_toggle_units(no_pref=False))
  1266. # ##################################### Workspace Setting Signals ###########################################
  1267. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1268. self.on_workspace_modified)
  1269. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1270. self.on_workspace_modified
  1271. )
  1272. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1273. # ###########################################################################################################
  1274. # ######################################## GUI SETTINGS SIGNALS #############################################
  1275. # ###########################################################################################################
  1276. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1277. # ######################################## Tools related signals ############################################
  1278. # portability changed signal
  1279. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1280. # Object list
  1281. self.object_status_changed.connect(self.collection.on_collection_updated)
  1282. # when there are arguments at application startup this get launched
  1283. self.args_at_startup[list].connect(self.on_startup_args)
  1284. # ###########################################################################################################
  1285. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1286. # ###########################################################################################################
  1287. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1288. lambda: self.restore_extensions(ext_type='excellon'))
  1289. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1290. lambda: self.restore_extensions(ext_type='gcode'))
  1291. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1292. lambda: self.restore_extensions(ext_type='gerber'))
  1293. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1294. lambda: self.delete_all_extensions(ext_type='excellon'))
  1295. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1296. lambda: self.delete_all_extensions(ext_type='gcode'))
  1297. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1298. lambda: self.delete_all_extensions(ext_type='gerber'))
  1299. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1300. lambda: self.add_extension(ext_type='excellon'))
  1301. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1302. lambda: self.add_extension(ext_type='gcode'))
  1303. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1304. lambda: self.add_extension(ext_type='gerber'))
  1305. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1306. lambda: self.del_extension(ext_type='excellon'))
  1307. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1308. lambda: self.del_extension(ext_type='gcode'))
  1309. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1310. lambda: self.del_extension(ext_type='gerber'))
  1311. # connect the 'Apply' buttons from the Preferences/File Associations
  1312. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1313. lambda: self.on_register_files(obj_type='excellon'))
  1314. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1315. lambda: self.on_register_files(obj_type='gcode'))
  1316. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1317. lambda: self.on_register_files(obj_type='gerber'))
  1318. # ###########################################################################################################
  1319. # ########################################### KEYWORDS SIGNALS ##############################################
  1320. # ###########################################################################################################
  1321. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1322. lambda: self.restore_extensions(ext_type='keyword'))
  1323. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1324. lambda: self.delete_all_extensions(ext_type='keyword'))
  1325. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1326. lambda: self.add_extension(ext_type='keyword'))
  1327. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1328. lambda: self.del_extension(ext_type='keyword'))
  1329. # ###########################################################################################################
  1330. # ########################################### GUI SIGNALS ###################################################
  1331. # ###########################################################################################################
  1332. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1333. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1334. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1335. # ###########################################################################################################
  1336. # ####################################### VARIOUS SIGNALS ###################################################
  1337. # ###########################################################################################################
  1338. # connect the abort_all_tasks related slots to the related signals
  1339. self.proc_container.idle_flag.connect(self.app_is_idle)
  1340. # signal emitted when a tab is closed in the Plot Area
  1341. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1342. # signal to close the application
  1343. self.close_app_signal.connect(self.kill_app)
  1344. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1345. # ###########################################################################################################
  1346. # ###########################################################################################################
  1347. # ###########################################################################################################
  1348. self.log.debug("Finished connecting Signals.")
  1349. # ###########################################################################################################
  1350. # ##################################### Finished the CONSTRUCTOR ############################################
  1351. # ###########################################################################################################
  1352. self.log.debug("END of constructor. Releasing control.")
  1353. # ###########################################################################################################
  1354. # ########################################## SHOW GUI #######################################################
  1355. # ###########################################################################################################
  1356. # if the app is not started as headless, show it
  1357. if self.cmd_line_headless != 1:
  1358. if show_splash:
  1359. # finish the splash
  1360. self.splash.finish(self.ui)
  1361. mgui_settings = QSettings("Open Source", "FlatCAM")
  1362. if mgui_settings.contains("maximized_gui"):
  1363. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1364. if maximized_ui is True:
  1365. self.ui.showMaximized()
  1366. else:
  1367. self.ui.show()
  1368. else:
  1369. self.ui.show()
  1370. if self.defaults["global_systray_icon"]:
  1371. self.trayIcon.show()
  1372. else:
  1373. log.warning("******************* RUNNING HEADLESS *******************")
  1374. # ###########################################################################################################
  1375. # ######################################## START-UP ARGUMENTS ###############################################
  1376. # ###########################################################################################################
  1377. # test if the program was started with a script as parameter
  1378. if self.cmd_line_shellvar:
  1379. try:
  1380. cnt = 0
  1381. command_tcl = 0
  1382. for i in self.cmd_line_shellvar.split(','):
  1383. if i is not None:
  1384. # noinspection PyBroadException
  1385. try:
  1386. command_tcl = eval(i)
  1387. except Exception:
  1388. command_tcl = i
  1389. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1390. cnt += 1
  1391. # if there are Windows paths then replace the path separator with a Unix like one
  1392. if sys.platform == 'win32':
  1393. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1394. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1395. except Exception as ext:
  1396. print("ERROR: ", ext)
  1397. sys.exit(2)
  1398. if self.cmd_line_shellfile:
  1399. if self.cmd_line_headless != 1:
  1400. if self.ui.shell_dock.isHidden():
  1401. self.ui.shell_dock.show()
  1402. try:
  1403. with open(self.cmd_line_shellfile, "r") as myfile:
  1404. # if show_splash:
  1405. # self.splash.showMessage('%s: %ssec\n%s' % (
  1406. # _("Canvas initialization started.\n"
  1407. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1408. # _("Executing Tcl Script ...")),
  1409. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1410. # color=QtGui.QColor("gray"))
  1411. cmd_line_shellfile_text = myfile.read()
  1412. if self.cmd_line_headless != 1:
  1413. self.shell.exec_command(cmd_line_shellfile_text)
  1414. else:
  1415. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1416. except Exception as ext:
  1417. print("ERROR: ", ext)
  1418. sys.exit(2)
  1419. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1420. # the path/file_name must be enclosed in quotes if it contain spaces
  1421. if App.args:
  1422. self.args_at_startup.emit(App.args)
  1423. if self.defaults.old_defaults_found is True:
  1424. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1425. "Please reboot the application to update."))
  1426. self.defaults.old_defaults_found = False
  1427. # ######################################### INIT FINISHED #######################################################
  1428. # #################################################################################################################
  1429. # #################################################################################################################
  1430. # #################################################################################################################
  1431. # #################################################################################################################
  1432. # #################################################################################################################
  1433. @staticmethod
  1434. def copy_and_overwrite(from_path, to_path):
  1435. """
  1436. From here:
  1437. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1438. :param from_path: source path
  1439. :param to_path: destination path
  1440. :return: None
  1441. """
  1442. if os.path.exists(to_path):
  1443. shutil.rmtree(to_path)
  1444. try:
  1445. shutil.copytree(from_path, to_path)
  1446. except FileNotFoundError:
  1447. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1448. shutil.copytree(from_new_path, to_path)
  1449. def on_startup_args(self, args, silent=False):
  1450. """
  1451. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1452. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1453. :param args: a list containing the application args at startup
  1454. :return: None
  1455. """
  1456. if args is not None:
  1457. args_to_process = args
  1458. else:
  1459. args_to_process = App.args
  1460. self.log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1461. for argument in args_to_process:
  1462. if '.FlatPrj'.lower() in argument.lower():
  1463. try:
  1464. project_name = str(argument)
  1465. if project_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Cancelled."))
  1468. else:
  1469. # self.open_project(project_name)
  1470. run_from_arg = True
  1471. # self.worker_task.emit({'fcn': self.open_project,
  1472. # 'params': [project_name, run_from_arg]})
  1473. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1474. except Exception as e:
  1475. self.log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1476. elif '.FlatConfig'.lower() in argument.lower():
  1477. try:
  1478. file_name = str(argument)
  1479. if file_name == "":
  1480. if silent is False:
  1481. self.inform.emit(_("Open Config file failed."))
  1482. else:
  1483. run_from_arg = True
  1484. # self.worker_task.emit({'fcn': self.open_config_file,
  1485. # 'params': [file_name, run_from_arg]})
  1486. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1487. except Exception as e:
  1488. self.log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1489. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1490. try:
  1491. file_name = str(argument)
  1492. if file_name == "":
  1493. if silent is False:
  1494. self.inform.emit(_("Open Script file failed."))
  1495. else:
  1496. if silent is False:
  1497. self.on_fileopenscript(name=file_name)
  1498. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1499. self.on_filerunscript(name=file_name)
  1500. except Exception as e:
  1501. self.log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1502. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1503. self.log.debug("App.on_startup_args() --> Quit event.")
  1504. sys.exit()
  1505. elif 'save'.lower() in argument.lower():
  1506. self.log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1507. self.preferencesUiManager.save_defaults()
  1508. else:
  1509. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1510. proc_arg = argument.lower()
  1511. for ext in exc_list:
  1512. proc_ext = ext.replace(' ', '')
  1513. proc_ext = '.%s' % proc_ext
  1514. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1515. file_name = str(argument)
  1516. if file_name == "":
  1517. if silent is False:
  1518. self.inform.emit(_("Open Excellon file failed."))
  1519. else:
  1520. self.on_fileopenexcellon(name=file_name, signal=None)
  1521. return
  1522. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1523. for ext in gco_list:
  1524. proc_ext = ext.replace(' ', '')
  1525. proc_ext = '.%s' % proc_ext
  1526. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1527. file_name = str(argument)
  1528. if file_name == "":
  1529. if silent is False:
  1530. self.inform.emit(_("Open GCode file failed."))
  1531. else:
  1532. self.on_fileopengcode(name=file_name, signal=None)
  1533. return
  1534. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1535. for ext in grb_list:
  1536. proc_ext = ext.replace(' ', '')
  1537. proc_ext = '.%s' % proc_ext
  1538. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1539. file_name = str(argument)
  1540. if file_name == "":
  1541. if silent is False:
  1542. self.inform.emit(_("Open Gerber file failed."))
  1543. else:
  1544. self.on_fileopengerber(name=file_name, signal=None)
  1545. return
  1546. # if it reached here without already returning then the app was registered with a file that it does not
  1547. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1548. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1549. # for arg in args_to_process:
  1550. # if 'FlatCAM.exe' in arg:
  1551. # continue
  1552. # else:
  1553. # sys.exit(2)
  1554. def tools_database_path(self):
  1555. return os.path.join(self.data_path, 'tools_db.FlatDB')
  1556. def defaults_path(self):
  1557. return os.path.join(self.data_path, 'current_defaults.FlatConfig')
  1558. def factory_defaults_path(self):
  1559. return os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  1560. def recent_files_path(self):
  1561. return os.path.join(self.data_path, 'recent.json')
  1562. def recent_projects_path(self):
  1563. return os.path.join(self.data_path, 'recent_projects.json')
  1564. def preprocessors_path(self):
  1565. return os.path.join(self.data_path, 'preprocessors')
  1566. def on_app_restart(self):
  1567. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1568. # be left in the SySTray
  1569. try:
  1570. self.trayIcon.hide()
  1571. except Exception:
  1572. pass
  1573. fcTranslate.restart_program(app=self)
  1574. def clear_pool(self):
  1575. """
  1576. Clear the multiprocessing pool and calls garbage collector.
  1577. :return: None
  1578. """
  1579. self.pool.close()
  1580. self.pool = Pool()
  1581. self.pool_recreated.emit(self.pool)
  1582. gc.collect()
  1583. def install_tools(self):
  1584. """
  1585. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1586. Instantiation of the Tools classes.
  1587. The order that the tools are installed is important as they can depend on each other install position.
  1588. :return: None
  1589. """
  1590. # shell tool has to be initialized always first because other tools print messages in the Shell Dock, but only if it not al´ready exists
  1591. if (hasattr(self,"shell") and self.shell is None) or hasattr(self,"shell")==False:
  1592. self.shell = FCShell(app=self, version=self.version)
  1593. self.distance_tool = Distance(self)
  1594. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1595. before=self.ui.menueditorigin,
  1596. separator=False)
  1597. self.distance_min_tool = DistanceMin(self)
  1598. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1599. pos=self.ui.menuedit,
  1600. before=self.ui.menueditorigin,
  1601. separator=True)
  1602. self.dblsidedtool = DblSidedTool(self)
  1603. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1604. self.cal_exc_tool = ToolCalibration(self)
  1605. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1606. before=self.dblsidedtool.menuAction,
  1607. separator=False)
  1608. self.align_objects_tool = AlignObjects(self)
  1609. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1610. self.edrills_tool = ToolExtractDrills(self)
  1611. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1612. self.panelize_tool = Panelize(self)
  1613. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1614. self.film_tool = Film(self)
  1615. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1616. self.paste_tool = SolderPaste(self)
  1617. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1618. self.calculator_tool = ToolCalculator(self)
  1619. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1620. self.sub_tool = ToolSub(self)
  1621. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1622. pos=self.ui.menutool, separator=True)
  1623. self.rules_tool = RulesCheck(self)
  1624. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1625. pos=self.ui.menutool, separator=False)
  1626. self.optimal_tool = ToolOptimal(self)
  1627. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1628. pos=self.ui.menutool, separator=True)
  1629. self.move_tool = ToolMove(self)
  1630. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1631. before=self.ui.menueditorigin, separator=True)
  1632. self.cutout_tool = CutOut(self)
  1633. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1634. before=self.sub_tool.menuAction)
  1635. self.ncclear_tool = NonCopperClear(self)
  1636. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1637. before=self.sub_tool.menuAction, separator=True)
  1638. self.paint_tool = ToolPaint(self)
  1639. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1640. before=self.sub_tool.menuAction, separator=True)
  1641. self.isolation_tool = ToolIsolation(self)
  1642. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1643. before=self.sub_tool.menuAction, separator=True)
  1644. self.drilling_tool = ToolDrilling(self)
  1645. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1646. before=self.sub_tool.menuAction, separator=True)
  1647. self.copper_thieving_tool = ToolCopperThieving(self)
  1648. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1649. pos=self.ui.menutool)
  1650. self.fiducial_tool = ToolFiducials(self)
  1651. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1652. pos=self.ui.menutool)
  1653. self.qrcode_tool = QRCode(self)
  1654. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1655. pos=self.ui.menutool)
  1656. self.punch_tool = ToolPunchGerber(self)
  1657. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1658. self.invert_tool = ToolInvertGerber(self)
  1659. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1660. self.corners_tool = ToolCorners(self)
  1661. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1662. self.etch_tool = ToolEtchCompensation(self)
  1663. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1664. self.transform_tool = ToolTransform(self)
  1665. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1666. pos=self.ui.menuoptions, separator=True)
  1667. self.properties_tool = Properties(self)
  1668. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1669. pos=self.ui.menuoptions)
  1670. self.pdf_tool = ToolPDF(self)
  1671. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1672. pos=self.ui.menufileimport,
  1673. separator=True)
  1674. self.image_tool = ToolImage(self)
  1675. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1676. pos=self.ui.menufileimport,
  1677. separator=True)
  1678. self.pcb_wizard_tool = PcbWizard(self)
  1679. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1680. pos=self.ui.menufileimport)
  1681. self.log.debug("Tools are installed.")
  1682. def remove_tools(self):
  1683. """
  1684. Will remove all the actions in the Tool menu.
  1685. :return: None
  1686. """
  1687. for act in self.ui.menutool.actions():
  1688. self.ui.menutool.removeAction(act)
  1689. def init_tools(self):
  1690. """
  1691. Initialize the Tool tab in the notebook side of the central widget.
  1692. Remove the actions in the Tools menu.
  1693. Instantiate again the FlatCAM tools (plugins).
  1694. All this is required when changing the layout: standard, compact etc.
  1695. :return: None
  1696. """
  1697. self.log.debug("init_tools()")
  1698. # delete the data currently in the Tools Tab and the Tab itself
  1699. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1700. if widget is not None:
  1701. widget.deleteLater()
  1702. self.ui.notebook.removeTab(2)
  1703. # rebuild the Tools Tab
  1704. self.ui.tool_tab = QtWidgets.QWidget()
  1705. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1706. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1707. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1708. self.ui.tool_scroll_area = VerticalScrollArea()
  1709. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1710. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1711. # first remove all of them
  1712. self.remove_tools()
  1713. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1714. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1715. '&Command Line\tS')
  1716. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1717. # third install all of them
  1718. try:
  1719. self.install_tools()
  1720. except AttributeError:
  1721. pass
  1722. self.log.debug("Tools are initialized.")
  1723. # def parse_system_fonts(self):
  1724. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1725. # 'params': []})
  1726. def connect_tools_signals_to_toolbar(self):
  1727. self.log.debug(" -> Connecting Tools Toolbar Signals")
  1728. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1729. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1730. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1731. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1732. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1733. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1734. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1735. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1736. self.ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1737. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1738. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1739. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1740. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1741. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1742. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1743. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1744. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1745. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1746. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1747. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1748. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1749. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1750. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1751. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1752. def connect_editors_toolbar_signals(self):
  1753. self.log.debug(" -> Connecting Editors Toolbar Signals")
  1754. # Geometry Editor Toolbar Signals
  1755. self.geo_editor.connect_geo_toolbar_signals()
  1756. # Gerber Editor Toolbar Signals
  1757. self.grb_editor.connect_grb_toolbar_signals()
  1758. # Excellon Editor Toolbar Signals
  1759. self.exc_editor.connect_exc_toolbar_signals()
  1760. def connect_toolbar_signals(self):
  1761. """
  1762. Reconnect the signals to the actions in the toolbar.
  1763. This has to be done each time after the FlatCAM tools are removed/installed.
  1764. :return: None
  1765. """
  1766. self.log.debug(" -> Connecting Toolbar Signals")
  1767. # Toolbar
  1768. # File Toolbar Signals
  1769. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1770. self.ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1771. self.ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1772. self.ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1773. self.ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1774. # View Toolbar Signals
  1775. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1776. self.ui.replot_btn.triggered.connect(self.plot_all)
  1777. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1778. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1779. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1780. # Edit Toolbar Signals
  1781. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1782. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1783. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1784. self.ui.delete_btn.triggered.connect(self.on_delete)
  1785. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1786. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1787. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1788. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1789. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1790. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1791. # Scripting Toolbar Signals
  1792. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1793. self.ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1794. self.ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1795. self.ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1796. # Tools Toolbar Signals
  1797. try:
  1798. self.connect_tools_signals_to_toolbar()
  1799. except Exception as err:
  1800. self.log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1801. def on_layout(self, index=None, lay=None):
  1802. """
  1803. Set the toolbars layout (location)
  1804. :param index:
  1805. :param lay: Type of layout to be set on the toolbard
  1806. :return: None
  1807. """
  1808. self.defaults.report_usage("on_layout()")
  1809. self.log.debug(" ---> New Layout")
  1810. if lay:
  1811. current_layout = lay
  1812. else:
  1813. current_layout = self.ui.general_defaults_form.general_gui_group.layout_combo.get_value()
  1814. lay_settings = QSettings("Open Source", "FlatCAM")
  1815. lay_settings.setValue('layout', current_layout)
  1816. # This will write the setting to the platform specific storage.
  1817. del lay_settings
  1818. # first remove the toolbars:
  1819. self.log.debug(" -> Remove Toolbars")
  1820. try:
  1821. self.ui.removeToolBar(self.ui.toolbarfile)
  1822. self.ui.removeToolBar(self.ui.toolbaredit)
  1823. self.ui.removeToolBar(self.ui.toolbarview)
  1824. self.ui.removeToolBar(self.ui.toolbarshell)
  1825. self.ui.removeToolBar(self.ui.toolbartools)
  1826. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  1827. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  1828. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  1829. self.ui.removeToolBar(self.ui.toolbarshell)
  1830. except Exception:
  1831. pass
  1832. self.log.debug(" -> Add New Toolbars")
  1833. if current_layout == 'compact':
  1834. # ## TOOLBAR INSTALLATION # ##
  1835. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  1836. self.ui.toolbarfile.setObjectName('File_TB')
  1837. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  1838. self.ui.toolbaredit = QtWidgets.QToolBar('Edit Toolbar')
  1839. self.ui.toolbaredit.setObjectName('Edit_TB')
  1840. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbaredit)
  1841. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  1842. self.ui.toolbarshell.setObjectName('Shell_TB')
  1843. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  1844. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  1845. self.ui.toolbartools.setObjectName('Tools_TB')
  1846. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  1847. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  1848. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  1849. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  1850. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  1851. self.ui.toolbarview.setObjectName('View_TB')
  1852. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  1853. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  1854. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  1855. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  1856. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  1857. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  1858. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  1859. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  1860. else:
  1861. # ## TOOLBAR INSTALLATION # ##
  1862. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  1863. self.ui.toolbarfile.setObjectName('File_TB')
  1864. self.ui.addToolBar(self.ui.toolbarfile)
  1865. self.ui.toolbaredit = QtWidgets.QToolBar('Edit Toolbar')
  1866. self.ui.toolbaredit.setObjectName('Edit_TB')
  1867. self.ui.addToolBar(self.ui.toolbaredit)
  1868. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  1869. self.ui.toolbarview.setObjectName('View_TB')
  1870. self.ui.addToolBar(self.ui.toolbarview)
  1871. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  1872. self.ui.toolbarshell.setObjectName('Shell_TB')
  1873. self.ui.addToolBar(self.ui.toolbarshell)
  1874. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  1875. self.ui.toolbartools.setObjectName('Tools_TB')
  1876. self.ui.addToolBar(self.ui.toolbartools)
  1877. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  1878. # self.ui.exc_edit_toolbar.setVisible(False)
  1879. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  1880. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  1881. self.ui.addToolBarBreak()
  1882. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  1883. # self.ui.geo_edit_toolbar.setVisible(False)
  1884. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  1885. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  1886. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  1887. # self.ui.grb_edit_toolbar.setVisible(False)
  1888. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  1889. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  1890. if current_layout == 'minimal':
  1891. self.ui.toolbarview.setVisible(False)
  1892. self.ui.toolbarshell.setVisible(False)
  1893. self.ui.geo_edit_toolbar.setVisible(False)
  1894. self.ui.grb_edit_toolbar.setVisible(False)
  1895. self.ui.exc_edit_toolbar.setVisible(False)
  1896. self.ui.lock_toolbar(lock=True)
  1897. # add all the actions to the toolbars
  1898. self.ui.populate_toolbars()
  1899. try:
  1900. # reconnect all the signals to the toolbar actions
  1901. self.connect_toolbar_signals()
  1902. except Exception as e:
  1903. self.log.debug(
  1904. "App.on_layout() - connect toolbar signals -> %s" % str(e))
  1905. # Editor Toolbars Signals
  1906. try:
  1907. self.connect_editors_toolbar_signals()
  1908. except Exception as err:
  1909. self.log.debug("App.on_layout() - connect editor signals -> %s" % str(err))
  1910. self.ui.grid_snap_btn.setChecked(True)
  1911. self.ui.corner_snap_btn.setVisible(False)
  1912. self.ui.snap_magnet.setVisible(False)
  1913. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  1914. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  1915. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  1916. self.ui.grid_gap_link_cb.setChecked(True)
  1917. def object2editor(self):
  1918. """
  1919. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1920. :return: None
  1921. """
  1922. self.defaults.report_usage("object2editor()")
  1923. # disable the objects menu as it may interfere with the appEditors
  1924. self.ui.menuobjects.setDisabled(True)
  1925. edited_object = self.collection.get_active()
  1926. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1927. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1928. pass
  1929. else:
  1930. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1931. return
  1932. if isinstance(edited_object, GeometryObject):
  1933. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1934. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1935. # we set the notebook to hidden
  1936. # self.ui.splitter.setSizes([0, 1])
  1937. if edited_object.multigeo is True:
  1938. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1939. if len(sel_rows) > 1:
  1940. self.inform.emit('[WARNING_NOTCL] %s' %
  1941. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1942. "is not possible.\n"
  1943. "Edit only one geometry at a time."))
  1944. if not sel_rows:
  1945. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1946. return
  1947. # determine the tool dia of the selected tool
  1948. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1949. # now find the key in the edited_object.tools that has this tooldia
  1950. multi_tool = 1
  1951. for tool in edited_object.tools:
  1952. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1953. multi_tool = tool
  1954. break
  1955. self.log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1956. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1957. else:
  1958. self.log.debug("Editing SingleGeo Geometry with tool diameter.")
  1959. self.geo_editor.edit_fcgeometry(edited_object)
  1960. # set call source to the Editor we go into
  1961. self.call_source = 'geo_editor'
  1962. elif isinstance(edited_object, ExcellonObject):
  1963. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1964. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1965. if self.ui.splitter.sizes()[0] == 0:
  1966. self.ui.splitter.setSizes([1, 1])
  1967. self.exc_editor.edit_fcexcellon(edited_object)
  1968. # set call source to the Editor we go into
  1969. self.call_source = 'exc_editor'
  1970. elif isinstance(edited_object, GerberObject):
  1971. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1972. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1973. if self.ui.splitter.sizes()[0] == 0:
  1974. self.ui.splitter.setSizes([1, 1])
  1975. self.grb_editor.edit_fcgerber(edited_object)
  1976. # set call source to the Editor we go into
  1977. self.call_source = 'grb_editor'
  1978. # reset the following variables so the UI is built again after edit
  1979. edited_object.ui_build = False
  1980. elif isinstance(edited_object, CNCJobObject):
  1981. if self.ui.splitter.sizes()[0] == 0:
  1982. self.ui.splitter.setSizes([1, 1])
  1983. # set call source to the Editor we go into
  1984. self.call_source = 'gcode_editor'
  1985. self.gcode_editor.edit_fcgcode(edited_object)
  1986. # make sure that we can't select another object while in Editor Mode:
  1987. self.ui.project_frame.setDisabled(True)
  1988. for idx in range(self.ui.notebook.count()):
  1989. # store the Properties Tab text color here and change the color and text
  1990. if self.ui.notebook.tabText(idx) == _("Properties"):
  1991. self.old_tab_text_color = self.ui.notebook.tabBar.tabTextColor(idx)
  1992. self.ui.notebook.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  1993. self.ui.notebook.tabBar.setTabText(idx, _("Editor"))
  1994. # disable the Project Tab
  1995. if self.ui.notebook.tabText(idx) == _("Project"):
  1996. self.ui.notebook.tabBar.setTabEnabled(idx, False)
  1997. # delete any selection shape that might be active as they are not relevant in Editor
  1998. self.delete_selection_shape()
  1999. # hide the Tools Toolbar
  2000. tools_tb = self.ui.toolbartools
  2001. if tools_tb.isVisible():
  2002. self.old_state_of_tools_toolbar = True
  2003. tools_tb.hide()
  2004. else:
  2005. self.old_state_of_tools_toolbar = False
  2006. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  2007. self.ui.plot_tab_area.protectTab(0)
  2008. self.log.debug("######################### Starting the EDITOR ################################")
  2009. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2010. self.should_we_save = True
  2011. def editor2object(self, cleanup=None):
  2012. """
  2013. Transfers the Geometry or Excellon from it's editor to the current object.
  2014. :return: None
  2015. """
  2016. self.defaults.report_usage("editor2object()")
  2017. # re-enable the objects menu that was disabled on entry in Editor mode
  2018. self.ui.menuobjects.setDisabled(False)
  2019. # do not update a geometry or excellon object unless it comes out of an editor
  2020. if self.call_source != 'app':
  2021. edited_obj = self.collection.get_active()
  2022. if cleanup is None:
  2023. msgbox = QtWidgets.QMessageBox()
  2024. msgbox.setText(_("Do you want to save the edited object?"))
  2025. msgbox.setWindowTitle(_("Exit Editor"))
  2026. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2027. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2028. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2029. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2030. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2031. msgbox.setDefaultButton(bt_yes)
  2032. msgbox.exec_()
  2033. response = msgbox.clickedButton()
  2034. if response == bt_yes:
  2035. # show the Tools Toolbar
  2036. tools_tb = self.ui.toolbartools
  2037. if self.old_state_of_tools_toolbar is True:
  2038. tools_tb.show()
  2039. # clean the Tools Tab
  2040. self.ui.tool_scroll_area.takeWidget()
  2041. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2042. self.ui.notebook.setTabText(2, _("Tool"))
  2043. if edited_obj.kind == 'geometry':
  2044. obj_type = "Geometry"
  2045. self.geo_editor.update_fcgeometry(edited_obj)
  2046. # self.geo_editor.update_options(edited_obj)
  2047. # restore GUI to the Selected TAB
  2048. # Remove anything else in the appGUI
  2049. self.ui.tool_scroll_area.takeWidget()
  2050. # update the geo object options so it is including the bounding box values
  2051. try:
  2052. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  2053. edited_obj.options['xmin'] = xmin
  2054. edited_obj.options['ymin'] = ymin
  2055. edited_obj.options['xmax'] = xmax
  2056. edited_obj.options['ymax'] = ymax
  2057. except AttributeError as e:
  2058. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  2059. self.log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2060. edited_obj.build_ui()
  2061. edited_obj.plot()
  2062. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2063. elif edited_obj.kind == 'gerber':
  2064. obj_type = "Gerber"
  2065. self.grb_editor.update_fcgerber()
  2066. # self.grb_editor.update_options(edited_obj)
  2067. # delete the old object (the source object) if it was an empty one
  2068. try:
  2069. if len(edited_obj.solid_geometry) == 0:
  2070. old_name = edited_obj.options['name']
  2071. self.collection.delete_by_name(old_name)
  2072. except TypeError:
  2073. # if the solid_geometry is a single Polygon the len() will not work
  2074. # in any case, falling here means that we have something in the solid_geometry, even if only
  2075. # a single Polygon, therefore we pass this
  2076. pass
  2077. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2078. # restore GUI to the Selected TAB
  2079. # Remove anything else in the GUI
  2080. self.ui.properties_scroll_area.takeWidget()
  2081. elif edited_obj.kind == 'excellon':
  2082. obj_type = "Excellon"
  2083. self.exc_editor.update_fcexcellon(edited_obj)
  2084. # self.exc_editor.update_options(edited_obj)
  2085. # restore GUI to the Selected TAB
  2086. # Remove anything else in the GUI
  2087. self.ui.tool_scroll_area.takeWidget()
  2088. # delete the old object (the source object) if it was an empty one
  2089. # find if we have drills:
  2090. has_drills = None
  2091. for tt in edited_obj.tools:
  2092. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  2093. has_drills = True
  2094. break
  2095. # find if we have slots:
  2096. has_slots = None
  2097. for tt in edited_obj.tools:
  2098. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  2099. has_slots = True
  2100. break
  2101. if has_drills is None and has_slots is None:
  2102. old_name = edited_obj.options['name']
  2103. self.collection.delete_by_name(name=old_name)
  2104. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2105. elif edited_obj.kind == 'cncjob':
  2106. obj_type = "CNCJob"
  2107. self.gcode_editor.update_fcgcode(edited_obj)
  2108. # self.exc_editor.update_options(edited_obj)
  2109. # restore GUI to the Selected TAB
  2110. # Remove anything else in the GUI
  2111. self.ui.tool_scroll_area.takeWidget()
  2112. edited_obj.build_ui()
  2113. # close the open tab
  2114. for idx in range(self.ui.plot_tab_area.count()):
  2115. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2116. self.ui.plot_tab_area.closeTab(idx)
  2117. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2118. else:
  2119. self.inform.emit('[WARNING_NOTCL] %s' %
  2120. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2121. return
  2122. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  2123. elif response == bt_no:
  2124. # show the Tools Toolbar
  2125. tools_tb = self.ui.toolbartools
  2126. if self.old_state_of_tools_toolbar is True:
  2127. tools_tb.show()
  2128. # clean the Tools Tab
  2129. self.ui.tool_scroll_area.takeWidget()
  2130. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2131. self.ui.notebook.setTabText(2, _("Tool"))
  2132. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2133. if edited_obj.kind == 'geometry':
  2134. self.geo_editor.deactivate()
  2135. edited_obj.build_ui()
  2136. edited_obj.plot()
  2137. elif edited_obj.kind == 'gerber':
  2138. self.grb_editor.deactivate_grb_editor()
  2139. edited_obj.build_ui()
  2140. elif edited_obj.kind == 'excellon':
  2141. self.exc_editor.deactivate()
  2142. edited_obj.build_ui()
  2143. elif edited_obj.kind == 'cncjob':
  2144. self.gcode_editor.deactivate()
  2145. edited_obj.build_ui()
  2146. # close the open tab
  2147. for idx in range(self.ui.plot_tab_area.count()):
  2148. try:
  2149. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2150. self.ui.plot_tab_area.closeTab(idx)
  2151. except AttributeError:
  2152. continue
  2153. else:
  2154. self.inform.emit('[WARNING_NOTCL] %s' %
  2155. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2156. return
  2157. elif response == bt_cancel:
  2158. return
  2159. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2160. # edited_obj.build_ui()
  2161. # Switch notebook to Properties page
  2162. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2163. else:
  2164. # show the Tools Toolbar
  2165. tools_tb = self.ui.toolbartools
  2166. if self.old_state_of_tools_toolbar is True:
  2167. tools_tb.show()
  2168. if isinstance(edited_obj, GeometryObject):
  2169. self.geo_editor.deactivate()
  2170. elif isinstance(edited_obj, GerberObject):
  2171. self.grb_editor.deactivate_grb_editor()
  2172. elif isinstance(edited_obj, ExcellonObject):
  2173. self.exc_editor.deactivate()
  2174. else:
  2175. self.inform.emit('[WARNING_NOTCL] %s' %
  2176. _("Select a Gerber, Geometry or Excellon Object to update."))
  2177. return
  2178. # if notebook is hidden we show it
  2179. if self.ui.splitter.sizes()[0] == 0:
  2180. self.ui.splitter.setSizes([1, 1])
  2181. for idx in range(self.ui.notebook.count()):
  2182. # restore the Properties Tab text and color
  2183. if self.ui.notebook.tabText(idx) == _("Editor"):
  2184. self.ui.notebook.tabBar.setTabTextColor(idx, self.old_tab_text_color)
  2185. self.ui.notebook.tabBar.setTabText(idx, _("Properties"))
  2186. # enable the Project Tab
  2187. if self.ui.notebook.tabText(idx) == _("Project"):
  2188. self.ui.notebook.tabBar.setTabEnabled(idx, True)
  2189. # restore the call_source to app
  2190. self.call_source = 'app'
  2191. self.log.debug("######################### Closing the EDITOR ################################")
  2192. # edited_obj.plot()
  2193. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2194. self.ui.plot_tab_area.protectTab(0)
  2195. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2196. self.ui.project_frame.setDisabled(False)
  2197. def get_last_folder(self):
  2198. """
  2199. Get the folder path from where the last file was opened.
  2200. :return: String, last opened folder path
  2201. """
  2202. return self.defaults["global_last_folder"]
  2203. def get_last_save_folder(self):
  2204. """
  2205. Get the folder path from where the last file was saved.
  2206. :return: String, last saved folder path
  2207. """
  2208. loc = self.defaults["global_last_save_folder"]
  2209. if loc is None:
  2210. loc = self.defaults["global_last_folder"]
  2211. if loc is None:
  2212. loc = os.path.dirname(__file__)
  2213. return loc
  2214. @QtCore.pyqtSlot(str)
  2215. @QtCore.pyqtSlot(str, bool)
  2216. def info(self, msg, shell_echo=True):
  2217. """
  2218. Informs the user. Normally on the status bar, optionally
  2219. also on the shell.
  2220. :param msg: Text to write.
  2221. :type msg: str
  2222. :param shell_echo: Control if to display the message msg in the Shell
  2223. :type shell_echo: bool
  2224. :return: None
  2225. """
  2226. # Type of message in brackets at the beginning of the message.
  2227. match = re.search(r"\[(.*)\](.*)", msg)
  2228. if match:
  2229. level = match.group(1)
  2230. msg_ = match.group(2)
  2231. self.ui.fcinfo.set_status(str(msg_), level=level)
  2232. if shell_echo is True:
  2233. if level.lower() == "error":
  2234. self.shell_message(msg, error=True, show=True)
  2235. elif level.lower() == "warning":
  2236. self.shell_message(msg, warning=True, show=True)
  2237. elif level.lower() == "error_notcl":
  2238. self.shell_message(msg, error=True, show=False)
  2239. elif level.lower() == "warning_notcl":
  2240. self.shell_message(msg, warning=True, show=False)
  2241. elif level.lower() == "success":
  2242. self.shell_message(msg, success=True, show=False)
  2243. elif level.lower() == "selected":
  2244. self.shell_message(msg, selected=True, show=False)
  2245. else:
  2246. self.shell_message(msg, show=False)
  2247. else:
  2248. self.ui.fcinfo.set_status(str(msg), level="info")
  2249. # make sure that if the message is to clear the infobar with a space
  2250. # is not printed over and over on the shell
  2251. if msg != '' and shell_echo is True:
  2252. self.shell_message(msg)
  2253. def info_shell(self, msg, new_line=True):
  2254. self.shell_message(msg=msg, new_line=new_line)
  2255. def save_to_file(self, content_to_save, txt_content):
  2256. """
  2257. Save something to a file.
  2258. :return: None
  2259. """
  2260. self.defaults.report_usage("save_to_file")
  2261. self.log.debug("save_to_file()")
  2262. self.date = str(datetime.today()).rpartition('.')[0]
  2263. self.date = ''.join(c for c in self.date if c not in ':-')
  2264. self.date = self.date.replace(' ', '_')
  2265. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2266. path_to_save = self.defaults["global_last_save_folder"] if \
  2267. self.defaults["global_last_save_folder"] is not None else self.data_path
  2268. try:
  2269. filename, _f = FCFileSaveDialog.get_saved_filename(
  2270. caption=_("Save to file"),
  2271. directory=path_to_save + '/file_' + self.date,
  2272. ext_filter=filter__
  2273. )
  2274. except TypeError:
  2275. filename, _f = FCFileSaveDialog.get_saved_filename(
  2276. caption=_("Save to file"),
  2277. ext_filter=filter__)
  2278. filename = str(filename)
  2279. if filename == "":
  2280. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2281. return
  2282. else:
  2283. try:
  2284. with open(filename, 'w') as f:
  2285. ___ = f.read()
  2286. except PermissionError:
  2287. self.inform.emit('[WARNING] %s' %
  2288. _("Permission denied, saving not possible.\n"
  2289. "Most likely another app is holding the file open and not accessible."))
  2290. return
  2291. except IOError:
  2292. self.log.debug('Creating a new file ...')
  2293. f = open(filename, 'w')
  2294. f.close()
  2295. except Exception:
  2296. e = sys.exc_info()[0]
  2297. App.log.error("Could not load the file.")
  2298. App.log.error(str(e))
  2299. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2300. return
  2301. # Save content
  2302. if filename.rpartition('.')[2].lower() == 'html':
  2303. file_content = content_to_save
  2304. else:
  2305. file_content = txt_content
  2306. try:
  2307. with open(filename, "w") as f:
  2308. f.write(file_content)
  2309. except Exception:
  2310. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2311. return
  2312. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2313. def register_recent(self, kind, filename):
  2314. """
  2315. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2316. dictionary.
  2317. :param kind: type of file that was opened
  2318. :param filename: the path and file name for the file that was opened
  2319. :return:
  2320. """
  2321. self.log.debug("register_recent()")
  2322. self.log.debug(" %s" % kind)
  2323. self.log.debug(" %s" % filename)
  2324. record = {'kind': str(kind), 'filename': str(filename)}
  2325. if record in self.recent:
  2326. return
  2327. if record in self.recent_projects:
  2328. return
  2329. if record['kind'] == 'project':
  2330. self.recent_projects.insert(0, record)
  2331. else:
  2332. self.recent.insert(0, record)
  2333. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2334. self.recent.pop()
  2335. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2336. self.recent_projects.pop()
  2337. try:
  2338. f = open(self.data_path + '/recent.json', 'w')
  2339. except IOError:
  2340. App.log.error("Failed to open recent items file for writing.")
  2341. self.inform.emit('[ERROR_NOTCL] %s' %
  2342. _('Failed to open recent files file for writing.'))
  2343. return
  2344. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2345. f.close()
  2346. try:
  2347. fp = open(self.data_path + '/recent_projects.json', 'w')
  2348. except IOError:
  2349. App.log.error("Failed to open recent items file for writing.")
  2350. self.inform.emit('[ERROR_NOTCL] %s' %
  2351. _('Failed to open recent projects file for writing.'))
  2352. return
  2353. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2354. fp.close()
  2355. # Re-build the recent items menu
  2356. self.setup_recent_items()
  2357. def on_about(self):
  2358. """
  2359. Displays the "about" dialog found in the Menu --> Help.
  2360. :return: None
  2361. """
  2362. self.defaults.report_usage("on_about")
  2363. version = self.version
  2364. version_date = self.version_date
  2365. beta = self.beta
  2366. class AboutDialog(QtWidgets.QDialog):
  2367. def __init__(self, app, parent=None):
  2368. QtWidgets.QDialog.__init__(self, parent)
  2369. self.app = app
  2370. # Icon and title
  2371. self.setWindowIcon(parent.app_icon)
  2372. self.setWindowTitle(_("About"))
  2373. self.resize(600, 200)
  2374. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2375. # self.setStyleSheet(
  2376. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2377. # "background-attachment: fixed"
  2378. # )
  2379. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2380. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2381. # palette = QtGui.QPalette()
  2382. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2383. # self.setPalette(palette)
  2384. logo = QtWidgets.QLabel()
  2385. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2386. title = QtWidgets.QLabel(
  2387. "<font size=8><B>FlatCAM</B></font><BR>"
  2388. "{title}<BR>"
  2389. "<BR>"
  2390. "<BR>"
  2391. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2392. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2393. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2394. "<B>{issue}</B></a><BR>".format(
  2395. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2396. devel=_("Development"),
  2397. down=_("DOWNLOAD"),
  2398. issue=_("Issue tracker"))
  2399. )
  2400. title.setOpenExternalLinks(True)
  2401. closebtn = QtWidgets.QPushButton(_("Close"))
  2402. tab_widget = QtWidgets.QTabWidget()
  2403. description_label = QtWidgets.QLabel(
  2404. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2405. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2406. version=version,
  2407. beta=('BETA' if beta else ''),
  2408. date=version_date,
  2409. arch=platform.architecture()[0])
  2410. )
  2411. description_label.setOpenExternalLinks(True)
  2412. lic_lbl_header = QtWidgets.QLabel(
  2413. '%s:<br>%s<br>' % (
  2414. _('Licensed under the MIT license'),
  2415. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2416. "http://www.opensource.org/licenses/mit-license.php</a>"
  2417. )
  2418. )
  2419. lic_lbl_header.setOpenExternalLinks(True)
  2420. lic_lbl_body = QtWidgets.QLabel(
  2421. _(
  2422. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2423. 'of this software and associated documentation files (the "Software"), to deal\n'
  2424. 'in the Software without restriction, including without limitation the rights\n'
  2425. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2426. 'copies of the Software, and to permit persons to whom the Software is\n'
  2427. 'furnished to do so, subject to the following conditions:\n\n'
  2428. 'The above copyright notice and this permission notice shall be included in\n'
  2429. 'all copies or substantial portions of the Software.\n\n'
  2430. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2431. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2432. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2433. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2434. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2435. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2436. 'THE SOFTWARE.'
  2437. )
  2438. )
  2439. attributions_label = QtWidgets.QLabel(
  2440. _(
  2441. 'Some of the icons used are from the following sources:<br>'
  2442. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2443. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2444. 'title="Flaticon">www.flaticon.com</a></div>'
  2445. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2446. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2447. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2448. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2449. 'title="Flaticon">www.flaticon.com</a></div>'
  2450. )
  2451. )
  2452. attributions_label.setOpenExternalLinks(True)
  2453. # layouts
  2454. layout1 = QtWidgets.QVBoxLayout()
  2455. layout1_1 = QtWidgets.QHBoxLayout()
  2456. layout1_2 = QtWidgets.QHBoxLayout()
  2457. layout2 = QtWidgets.QHBoxLayout()
  2458. layout3 = QtWidgets.QHBoxLayout()
  2459. self.setLayout(layout1)
  2460. layout1.addLayout(layout1_1)
  2461. layout1.addLayout(layout1_2)
  2462. layout1.addLayout(layout2)
  2463. layout1.addLayout(layout3)
  2464. layout1_1.addStretch()
  2465. layout1_1.addWidget(description_label)
  2466. layout1_2.addWidget(tab_widget)
  2467. self.splash_tab = QtWidgets.QWidget()
  2468. self.splash_tab.setObjectName("splash_about")
  2469. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2470. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2471. tab_widget.addTab(self.splash_tab, _("Splash"))
  2472. self.programmmers_tab = QtWidgets.QWidget()
  2473. self.programmmers_tab.setObjectName("programmers_about")
  2474. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2475. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2476. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2477. self.translators_tab = QtWidgets.QWidget()
  2478. self.translators_tab.setObjectName("translators_about")
  2479. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2480. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2481. tab_widget.addTab(self.translators_tab, _("Translators"))
  2482. self.license_tab = QtWidgets.QWidget()
  2483. self.license_tab.setObjectName("license_about")
  2484. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2485. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2486. tab_widget.addTab(self.license_tab, _("License"))
  2487. self.attributions_tab = QtWidgets.QWidget()
  2488. self.attributions_tab.setObjectName("attributions_about")
  2489. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2490. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2491. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2492. self.splash_tab_layout.addWidget(logo, stretch=0)
  2493. self.splash_tab_layout.addWidget(title, stretch=1)
  2494. pal = QtGui.QPalette()
  2495. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2496. self.prog_grid_lay = QtWidgets.QGridLayout()
  2497. self.prog_grid_lay.setHorizontalSpacing(20)
  2498. self.prog_grid_lay.setColumnStretch(0, 0)
  2499. self.prog_grid_lay.setColumnStretch(2, 1)
  2500. prog_widget = QtWidgets.QWidget()
  2501. prog_widget.setLayout(self.prog_grid_lay)
  2502. prog_scroll = QtWidgets.QScrollArea()
  2503. prog_scroll.setWidget(prog_widget)
  2504. prog_scroll.setWidgetResizable(True)
  2505. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2506. prog_scroll.setPalette(pal)
  2507. self.programmmers_tab_layout.addWidget(prog_scroll)
  2508. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2509. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2510. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2511. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2512. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2513. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2514. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2515. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2516. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2517. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2518. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2519. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2520. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2521. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2522. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2523. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2524. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2525. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2526. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2527. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2528. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2529. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2530. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2531. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2532. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2533. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2534. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2535. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2536. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2537. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2538. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2539. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2540. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2541. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2542. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2543. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2544. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2545. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2546. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2547. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2548. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2549. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2550. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2551. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2552. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2553. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2554. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2555. self.translator_grid_lay = QtWidgets.QGridLayout()
  2556. self.translator_grid_lay.setColumnStretch(0, 0)
  2557. self.translator_grid_lay.setColumnStretch(1, 0)
  2558. self.translator_grid_lay.setColumnStretch(2, 1)
  2559. self.translator_grid_lay.setColumnStretch(3, 0)
  2560. # trans_widget = QtWidgets.QWidget()
  2561. # trans_widget.setLayout(self.translator_grid_lay)
  2562. # self.translators_tab_layout.addWidget(trans_widget)
  2563. # self.translators_tab_layout.addStretch()
  2564. trans_widget = QtWidgets.QWidget()
  2565. trans_widget.setLayout(self.translator_grid_lay)
  2566. trans_scroll = QtWidgets.QScrollArea()
  2567. trans_scroll.setWidget(trans_widget)
  2568. trans_scroll.setWidgetResizable(True)
  2569. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2570. trans_scroll.setPalette(pal)
  2571. self.translators_tab_layout.addWidget(trans_scroll)
  2572. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2573. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2574. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2575. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2576. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2577. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2578. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2579. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2580. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2581. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Olivier Cornet"), 2, 2)
  2582. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2583. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2584. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2585. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2586. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2587. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2588. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2589. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2590. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2591. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2592. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2593. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2594. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2595. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2596. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2597. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2598. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2599. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2600. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2601. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2602. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2603. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2604. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2605. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2606. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2607. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2608. self.translator_grid_lay.setColumnStretch(0, 0)
  2609. self.translators_tab_layout.addStretch()
  2610. self.license_tab_layout.addWidget(lic_lbl_header)
  2611. self.license_tab_layout.addWidget(lic_lbl_body)
  2612. self.license_tab_layout.addStretch()
  2613. self.attributions_tab_layout.addWidget(attributions_label)
  2614. self.attributions_tab_layout.addStretch()
  2615. layout3.addStretch()
  2616. layout3.addWidget(closebtn)
  2617. closebtn.clicked.connect(self.accept)
  2618. AboutDialog(app=self, parent=self.ui).exec_()
  2619. def on_howto(self):
  2620. """
  2621. Displays the "about" dialog found in the Menu --> Help.
  2622. :return: None
  2623. """
  2624. class HowtoDialog(QtWidgets.QDialog):
  2625. def __init__(self, app, parent=None):
  2626. QtWidgets.QDialog.__init__(self, parent)
  2627. self.app = app
  2628. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2629. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2630. "<b>click</b></a>"
  2631. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2632. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2633. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2634. # Icon and title
  2635. self.setWindowIcon(parent.app_icon)
  2636. self.setWindowTitle('%s ...' % _("How To"))
  2637. self.resize(750, 375)
  2638. logo = QtWidgets.QLabel()
  2639. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2640. # content = QtWidgets.QLabel(
  2641. # "%s<br>"
  2642. # "%s<br><br>"
  2643. # "%s,<br>"
  2644. # "%s<br>"
  2645. # "<ul>"
  2646. # "<li> &nbsp;%s %s</li>"
  2647. # "<li> &nbsp;%s %s</li>"
  2648. # "</ul>"
  2649. # "%s %s.<br>"
  2650. # "%s"
  2651. # "<ul>"
  2652. # "<li> &nbsp;%s &#128077;</li>"
  2653. # "<li> &nbsp;%s &#128513;</li>"
  2654. # "</ul>" %
  2655. # (
  2656. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2657. # _("Yet it cannot evolve without <b>contributions</b>."),
  2658. # _("If you want to see this application grow and become better and better"),
  2659. # _("you can <b>contribute</b> to the development yourself by:"),
  2660. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2661. # new_features_link,
  2662. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2663. # bugs_link,
  2664. # _("If you like or use this program you can make a donation"),
  2665. # donation_link,
  2666. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2667. # _("it will be welcomed with joy"),
  2668. # _("it will give me a reason to continue")
  2669. # )
  2670. # )
  2671. # font-weight: bold;
  2672. content = QtWidgets.QLabel(
  2673. "%s<br>"
  2674. "%s<br><br>"
  2675. "%s,<br>"
  2676. "%s<br>"
  2677. "<ul>"
  2678. "<li> &nbsp;%s %s</li>"
  2679. "<li> &nbsp;%s %s</li>"
  2680. "</ul>"
  2681. "<br><br>"
  2682. "%s <br>"
  2683. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2684. (
  2685. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2686. _("Yet it cannot evolve without <b>contributions</b>."),
  2687. _("If you want to see this application grow and become better and better"),
  2688. _("you can <b>contribute</b> to the development yourself by:"),
  2689. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2690. new_features_link,
  2691. _("Bug Reports by providing the steps required to reproduce the bug"),
  2692. bugs_link,
  2693. _("If you like what you have seen so far ..."),
  2694. _("Donations are NOT required."), _("But they are welcomed"),
  2695. donation_link
  2696. )
  2697. )
  2698. content.setOpenExternalLinks(True)
  2699. # palette
  2700. pal = QtGui.QPalette()
  2701. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2702. # layouts
  2703. main_layout = QtWidgets.QVBoxLayout()
  2704. self.setLayout(main_layout)
  2705. tab_layout = QtWidgets.QHBoxLayout()
  2706. buttons_hlay = QtWidgets.QHBoxLayout()
  2707. main_layout.addLayout(tab_layout)
  2708. main_layout.addLayout(buttons_hlay)
  2709. tab_widget = QtWidgets.QTabWidget()
  2710. tab_layout.addWidget(tab_widget)
  2711. closebtn = QtWidgets.QPushButton(_("Close"))
  2712. buttons_hlay.addStretch()
  2713. buttons_hlay.addWidget(closebtn)
  2714. # CONTRIBUTE section
  2715. self.intro_tab = QtWidgets.QWidget()
  2716. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2717. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2718. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2719. self.grid_lay = QtWidgets.QGridLayout()
  2720. self.grid_lay.setHorizontalSpacing(20)
  2721. self.grid_lay.setColumnStretch(0, 0)
  2722. self.grid_lay.setColumnStretch(1, 1)
  2723. intro_wdg = QtWidgets.QWidget()
  2724. intro_wdg.setLayout(self.grid_lay)
  2725. intro_scroll_area = QtWidgets.QScrollArea()
  2726. intro_scroll_area.setWidget(intro_wdg)
  2727. intro_scroll_area.setWidgetResizable(True)
  2728. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2729. intro_scroll_area.setPalette(pal)
  2730. self.grid_lay.addWidget(logo, 0, 0)
  2731. self.grid_lay.addWidget(content, 0, 1)
  2732. self.intro_tab_layout.addWidget(intro_scroll_area)
  2733. # LINKS EXCHANGE section
  2734. self.links_tab = QtWidgets.QWidget()
  2735. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2736. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2737. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2738. self.links_lay = QtWidgets.QHBoxLayout()
  2739. links_wdg = QtWidgets.QWidget()
  2740. links_wdg.setLayout(self.links_lay)
  2741. links_scroll_area = QtWidgets.QScrollArea()
  2742. links_scroll_area.setWidget(links_wdg)
  2743. links_scroll_area.setWidgetResizable(True)
  2744. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2745. links_scroll_area.setPalette(pal)
  2746. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2747. self.links_tab_layout.addWidget(links_scroll_area)
  2748. # HOW TO section
  2749. self.howto_tab = QtWidgets.QWidget()
  2750. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2751. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2752. tab_widget.addTab(self.howto_tab, _("How To's"))
  2753. self.howto_lay = QtWidgets.QHBoxLayout()
  2754. howto_wdg = QtWidgets.QWidget()
  2755. howto_wdg.setLayout(self.howto_lay)
  2756. howto_scroll_area = QtWidgets.QScrollArea()
  2757. howto_scroll_area.setWidget(howto_wdg)
  2758. howto_scroll_area.setWidgetResizable(True)
  2759. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2760. howto_scroll_area.setPalette(pal)
  2761. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2762. self.howto_tab_layout.addWidget(howto_scroll_area)
  2763. # BUTTONS section
  2764. closebtn.clicked.connect(self.accept)
  2765. HowtoDialog(app=self, parent=self.ui).exec_()
  2766. def install_bookmarks(self, book_dict=None):
  2767. """
  2768. Install the bookmarks actions in the Help menu -> Bookmarks
  2769. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2770. :return: None
  2771. """
  2772. if book_dict is None:
  2773. self.defaults["global_bookmarks"].update(
  2774. {
  2775. '1': ['FlatCAM', "http://flatcam.org"],
  2776. '2': [_('Backup Site'), ""]
  2777. }
  2778. )
  2779. else:
  2780. self.defaults["global_bookmarks"].clear()
  2781. self.defaults["global_bookmarks"].update(book_dict)
  2782. # first try to disconnect if somehow they get connected from elsewhere
  2783. for act in self.ui.menuhelp_bookmarks.actions():
  2784. try:
  2785. act.triggered.disconnect()
  2786. except TypeError:
  2787. pass
  2788. # clear all actions except the last one who is the Bookmark manager
  2789. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2790. pass
  2791. else:
  2792. self.ui.menuhelp_bookmarks.removeAction(act)
  2793. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2794. if self.defaults["global_bookmarks"]:
  2795. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2796. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2797. # the JSON is first making the keys as strings (therefore I have to use strings too
  2798. # or do the conversion :(
  2799. # )
  2800. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2801. # the '10' entry jsut after '1' therefore ordering as strings
  2802. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2803. key=lambda x: int(x[0]))
  2804. for entry, bookmark in sorted_bookmarks:
  2805. title = bookmark[0]
  2806. weblink = bookmark[1]
  2807. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2808. act.setText(title)
  2809. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2810. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2811. if title == _('Backup Site') and weblink == "":
  2812. act.triggered.connect(self.on_backup_site)
  2813. else:
  2814. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2815. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2816. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2817. def on_bookmarks_manager(self):
  2818. """
  2819. Adds the bookmark manager in a Tab in Plot Area
  2820. :return:
  2821. """
  2822. for idx in range(self.ui.plot_tab_area.count()):
  2823. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2824. # there can be only one instance of Bookmark Manager at one time
  2825. return
  2826. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2827. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2828. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2829. # add the tab if it was closed
  2830. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2831. # delete the absolute and relative position and messages in the infobar
  2832. # self.ui.position_label.setText("")
  2833. # self.ui.rel_position_label.setText("")
  2834. # hide coordinates toolbars in the infobar while in DB
  2835. self.ui.coords_toolbar.hide()
  2836. self.ui.delta_coords_toolbar.hide()
  2837. # Switch plot_area to preferences page
  2838. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2839. def on_backup_site(self):
  2840. msgbox = QtWidgets.QMessageBox()
  2841. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2842. "1. FlatCAM.org website is down\n"
  2843. "2. Someone forked FlatCAM project and wants to point\n"
  2844. "to his own website\n\n"
  2845. "If you can't get any informations about the application\n"
  2846. "use the YouTube channel link from the Help menu."))
  2847. msgbox.setWindowTitle(_("Alternative website"))
  2848. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2849. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2850. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2851. msgbox.setDefaultButton(bt_yes)
  2852. msgbox.exec_()
  2853. # response = msgbox.clickedButton()
  2854. def final_save(self):
  2855. """
  2856. Callback for doing a preferences save to file whenever the application is about to quit.
  2857. If the project has changes, it will ask the user to save the project.
  2858. :return: None
  2859. """
  2860. if self.save_in_progress:
  2861. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2862. return
  2863. if self.should_we_save and self.collection.get_list():
  2864. msgbox = QtWidgets.QMessageBox()
  2865. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2866. "\n"
  2867. "Do you want to Save the project?"))
  2868. msgbox.setWindowTitle(_("Save changes"))
  2869. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2870. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2871. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2872. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2873. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2874. msgbox.setDefaultButton(bt_yes)
  2875. msgbox.exec_()
  2876. response = msgbox.clickedButton()
  2877. if response == bt_yes:
  2878. try:
  2879. self.trayIcon.hide()
  2880. except Exception:
  2881. pass
  2882. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2883. elif response == bt_no:
  2884. try:
  2885. self.trayIcon.hide()
  2886. except Exception:
  2887. pass
  2888. self.quit_application()
  2889. elif response == bt_cancel:
  2890. return
  2891. else:
  2892. try:
  2893. self.trayIcon.hide()
  2894. except Exception:
  2895. pass
  2896. self.quit_application()
  2897. def quit_application(self):
  2898. """
  2899. Called (as a pyslot or not) when the application is quit.
  2900. :return: None
  2901. """
  2902. # close editors before quiting the app, if they are open
  2903. if self.call_source == 'geo_editor':
  2904. self.geo_editor.deactivate()
  2905. try:
  2906. self.geo_editor.disconnect()
  2907. except TypeError:
  2908. pass
  2909. self.log.debug("App.quit_application() --> Geo Editor deactivated.")
  2910. if self.call_source == 'exc_editor':
  2911. self.exc_editor.deactivate()
  2912. try:
  2913. self.grb_editor.disconnect()
  2914. except TypeError:
  2915. pass
  2916. self.log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2917. if self.call_source == 'grb_editor':
  2918. self.grb_editor.deactivate_grb_editor()
  2919. try:
  2920. self.exc_editor.disconnect()
  2921. except TypeError:
  2922. pass
  2923. self.log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2924. # disconnect the mouse events
  2925. if self.is_legacy:
  2926. self.plotcanvas.graph_event_disconnect(self.mm)
  2927. self.plotcanvas.graph_event_disconnect(self.mp)
  2928. self.plotcanvas.graph_event_disconnect(self.mr)
  2929. self.plotcanvas.graph_event_disconnect(self.mdc)
  2930. self.plotcanvas.graph_event_disconnect(self.kp)
  2931. else:
  2932. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2933. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2934. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2935. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2936. self.on_mouse_double_click_over_plot)
  2937. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2938. self.preferencesUiManager.save_defaults(silent=True)
  2939. self.log.debug("App.quit_application() --> App Defaults saved.")
  2940. if self.cmd_line_headless != 1:
  2941. # save app state to file
  2942. stgs = QSettings("Open Source", "FlatCAM")
  2943. stgs.setValue('saved_gui_state', self.ui.saveState())
  2944. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2945. stgs.setValue(
  2946. 'language',
  2947. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2948. )
  2949. stgs.setValue(
  2950. 'notebook_font_size',
  2951. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2952. )
  2953. stgs.setValue(
  2954. 'axis_font_size',
  2955. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2956. )
  2957. stgs.setValue(
  2958. 'textbox_font_size',
  2959. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2960. )
  2961. stgs.setValue(
  2962. 'hud_font_size',
  2963. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2964. )
  2965. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2966. stgs.setValue(
  2967. 'machinist',
  2968. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2969. )
  2970. # This will write the setting to the platform specific storage.
  2971. del stgs
  2972. self.log.debug("App.quit_application() --> App UI state saved.")
  2973. # try to quit the Socket opened by ArgsThread class
  2974. try:
  2975. # self.new_launch.thread_exit = True
  2976. # self.new_launch.listener.close()
  2977. self.new_launch.stop.emit()
  2978. except Exception as err:
  2979. self.log.debug("App.quit_application() --> %s" % str(err))
  2980. # try to quit the QThread that run ArgsThread class
  2981. try:
  2982. # del self.new_launch
  2983. self.listen_th.quit()
  2984. except Exception as e:
  2985. self.log.debug("App.quit_application() --> %s" % str(e))
  2986. # terminate workers
  2987. # self.workers.__del__()
  2988. self.clear_pool()
  2989. # quit app by signalling for self.kill_app() method
  2990. # self.close_app_signal.emit()
  2991. QtWidgets.qApp.quit()
  2992. sys.exit(0)
  2993. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2994. # we use the following command
  2995. # minor_v = sys.version_info.minor
  2996. # if minor_v < 8:
  2997. # # make sure that the app closes
  2998. # sys.exit(0)
  2999. # else:
  3000. # os._exit(0) # fix to work with Python 3.8
  3001. @staticmethod
  3002. def kill_app():
  3003. QtWidgets.qApp.quit()
  3004. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  3005. # we use the following command
  3006. sys.exit(0)
  3007. def on_portable_checked(self, state):
  3008. """
  3009. Callback called when the checkbox in Preferences GUI is checked.
  3010. It will set the application as portable by creating the preferences and recent files in the
  3011. 'config' folder found in the FlatCAM installation folder.
  3012. :param state: boolean, the state of the checkbox when clicked/checked
  3013. :return:
  3014. """
  3015. line_no = 0
  3016. data = None
  3017. if sys.platform != 'win32':
  3018. # this won't work in Linux or MacOS
  3019. return
  3020. # test if the app was frozen and choose the path for the configuration file
  3021. if getattr(sys, "frozen", False) is True:
  3022. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3023. else:
  3024. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3025. config_file = current_data_path + '\\configuration.txt'
  3026. try:
  3027. with open(config_file, 'r') as f:
  3028. try:
  3029. data = f.readlines()
  3030. except Exception as e:
  3031. self.log.debug('App.__init__() -->%s' % str(e))
  3032. return
  3033. except FileNotFoundError:
  3034. pass
  3035. for line in data:
  3036. line = line.strip('\n')
  3037. param = str(line).rpartition('=')
  3038. if param[0] == 'portable':
  3039. break
  3040. line_no += 1
  3041. if state:
  3042. data[line_no] = 'portable=True\n'
  3043. # create the new defauults files
  3044. # create current_defaults.FlatConfig file if there is none
  3045. try:
  3046. f = open(current_data_path + '/current_defaults.FlatConfig')
  3047. f.close()
  3048. except IOError:
  3049. self.log.debug('Creating empty current_defaults.FlatConfig')
  3050. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3051. json.dump({}, f)
  3052. f.close()
  3053. # create factory_defaults.FlatConfig file if there is none
  3054. try:
  3055. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3056. f.close()
  3057. except IOError:
  3058. self.log.debug('Creating empty factory_defaults.FlatConfig')
  3059. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3060. json.dump({}, f)
  3061. f.close()
  3062. try:
  3063. f = open(current_data_path + '/recent.json')
  3064. f.close()
  3065. except IOError:
  3066. self.log.debug('Creating empty recent.json')
  3067. f = open(current_data_path + '/recent.json', 'w')
  3068. json.dump([], f)
  3069. f.close()
  3070. try:
  3071. fp = open(current_data_path + '/recent_projects.json')
  3072. fp.close()
  3073. except IOError:
  3074. self.log.debug('Creating empty recent_projects.json')
  3075. fp = open(current_data_path + '/recent_projects.json', 'w')
  3076. json.dump([], fp)
  3077. fp.close()
  3078. # save the current defaults to the new defaults file
  3079. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3080. else:
  3081. data[line_no] = 'portable=False\n'
  3082. with open(config_file, 'w') as f:
  3083. f.writelines(data)
  3084. def on_register_files(self, obj_type=None):
  3085. """
  3086. Called whenever there is a need to register file extensions with FlatCAM.
  3087. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3088. :param obj_type: the type of object to be register for.
  3089. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3090. :return: None
  3091. """
  3092. self.log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3093. new_reg_path = 'Software\\Classes\\'
  3094. # find if the current user is admin
  3095. try:
  3096. is_admin = os.getuid() == 0
  3097. except AttributeError:
  3098. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3099. if is_admin is True:
  3100. root_path = winreg.HKEY_LOCAL_MACHINE
  3101. else:
  3102. root_path = winreg.HKEY_CURRENT_USER
  3103. # create the keys
  3104. def set_reg(name, root_pth, new_reg_path_par, value):
  3105. try:
  3106. winreg.CreateKey(root_pth, new_reg_path_par)
  3107. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  3108. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3109. return True
  3110. except WindowsError:
  3111. return False
  3112. # delete key in registry
  3113. def delete_reg(root_pth, reg_path, key_to_del):
  3114. key_to_del_path = reg_path + key_to_del
  3115. try:
  3116. winreg.DeleteKey(root_pth, key_to_del_path)
  3117. return True
  3118. except WindowsError:
  3119. return False
  3120. if obj_type is None or obj_type == 'excellon':
  3121. exc_list = \
  3122. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3123. exc_list = [x for x in exc_list if x != '']
  3124. # register all keys in the Preferences window
  3125. for ext in exc_list:
  3126. new_k = new_reg_path + '.%s' % ext
  3127. set_reg('', root_pth=root_path, new_reg_path_par=new_k, value='FlatCAM')
  3128. # and unregister those that are no longer in the Preferences windows but are in the file
  3129. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3130. if ext not in exc_list:
  3131. delete_reg(root_pth=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3132. # now write the updated extensions to the self.defaults
  3133. # new_ext = ''
  3134. # for ext in exc_list:
  3135. # new_ext = new_ext + ext + ', '
  3136. # self.defaults["fa_excellon"] = new_ext
  3137. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3138. if obj_type is None or obj_type == 'gcode':
  3139. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3140. gco_list = [x for x in gco_list if x != '']
  3141. # register all keys in the Preferences window
  3142. for ext in gco_list:
  3143. new_k = new_reg_path + '.%s' % ext
  3144. set_reg('', root_pth=root_path, new_reg_path_par=new_k, value='FlatCAM')
  3145. # and unregister those that are no longer in the Preferences windows but are in the file
  3146. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3147. if ext not in gco_list:
  3148. delete_reg(root_pth=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3149. self.inform.emit('[success] %s' %
  3150. _("Selected GCode file extensions registered with FlatCAM."))
  3151. if obj_type is None or obj_type == 'gerber':
  3152. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3153. grb_list = [x for x in grb_list if x != '']
  3154. # register all keys in the Preferences window
  3155. for ext in grb_list:
  3156. new_k = new_reg_path + '.%s' % ext
  3157. set_reg('', root_pth=root_path, new_reg_path_par=new_k, value='FlatCAM')
  3158. # and unregister those that are no longer in the Preferences windows but are in the file
  3159. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3160. if ext not in grb_list:
  3161. delete_reg(root_pth=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3162. self.inform.emit('[success] %s' % _("Selected Gerber file extensions registered with FlatCAM."))
  3163. def add_extension(self, ext_type):
  3164. """
  3165. Add a file extension to the list for a specific object
  3166. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3167. :return:
  3168. """
  3169. if ext_type == 'excellon':
  3170. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3171. if new_ext == '':
  3172. return
  3173. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3174. if new_ext in old_val:
  3175. return
  3176. old_val.append(new_ext)
  3177. old_val.sort()
  3178. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3179. if ext_type == 'gcode':
  3180. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3181. if new_ext == '':
  3182. return
  3183. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3184. if new_ext in old_val:
  3185. return
  3186. old_val.append(new_ext)
  3187. old_val.sort()
  3188. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3189. if ext_type == 'gerber':
  3190. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3191. if new_ext == '':
  3192. return
  3193. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3194. if new_ext in old_val:
  3195. return
  3196. old_val.append(new_ext)
  3197. old_val.sort()
  3198. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3199. if ext_type == 'keyword':
  3200. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3201. if new_kw == '':
  3202. return
  3203. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3204. if new_kw in old_val:
  3205. return
  3206. old_val.append(new_kw)
  3207. old_val.sort()
  3208. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3209. # update the self.myKeywords so the model is updated
  3210. self.autocomplete_kw_list = \
  3211. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3212. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3213. self.shell.command_line().set_model_data(self.myKeywords)
  3214. def del_extension(self, ext_type):
  3215. """
  3216. Remove a file extension from the list for a specific object
  3217. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3218. :return:
  3219. """
  3220. if ext_type == 'excellon':
  3221. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3222. if new_ext == '':
  3223. return
  3224. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3225. if new_ext not in old_val:
  3226. return
  3227. old_val.remove(new_ext)
  3228. old_val.sort()
  3229. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3230. if ext_type == 'gcode':
  3231. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3232. if new_ext == '':
  3233. return
  3234. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3235. if new_ext not in old_val:
  3236. return
  3237. old_val.remove(new_ext)
  3238. old_val.sort()
  3239. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3240. if ext_type == 'gerber':
  3241. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3242. if new_ext == '':
  3243. return
  3244. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3245. if new_ext not in old_val:
  3246. return
  3247. old_val.remove(new_ext)
  3248. old_val.sort()
  3249. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3250. if ext_type == 'keyword':
  3251. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3252. if new_kw == '':
  3253. return
  3254. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3255. if new_kw not in old_val:
  3256. return
  3257. old_val.remove(new_kw)
  3258. old_val.sort()
  3259. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3260. # update the self.myKeywords so the model is updated
  3261. self.autocomplete_kw_list = \
  3262. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3263. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3264. self.shell.command_line().set_model_data(self.myKeywords)
  3265. def restore_extensions(self, ext_type):
  3266. """
  3267. Restore all file extensions associations with FlatCAM, for a specific object
  3268. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3269. :return:
  3270. """
  3271. if ext_type == 'excellon':
  3272. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3273. # for the ability to open Excellon files with .txt extension
  3274. new_exc_list = deepcopy(self.exc_list)
  3275. try:
  3276. new_exc_list.remove('txt')
  3277. except ValueError:
  3278. pass
  3279. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3280. if ext_type == 'gcode':
  3281. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3282. if ext_type == 'gerber':
  3283. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3284. if ext_type == 'keyword':
  3285. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3286. # update the self.myKeywords so the model is updated
  3287. self.autocomplete_kw_list = self.default_keywords
  3288. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3289. self.shell.commnad_line().set_model_data(self.myKeywords)
  3290. def delete_all_extensions(self, ext_type):
  3291. """
  3292. Delete all file extensions associations with FlatCAM, for a specific object
  3293. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3294. :return:
  3295. """
  3296. if ext_type == 'excellon':
  3297. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3298. if ext_type == 'gcode':
  3299. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3300. if ext_type == 'gerber':
  3301. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3302. if ext_type == 'keyword':
  3303. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3304. # update the self.myKeywords so the model is updated
  3305. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3306. self.shell.command_line().set_model_data(self.myKeywords)
  3307. def on_edit_join(self, name=None):
  3308. """
  3309. Callback for Edit->Join. Joins the selected geometry objects into
  3310. a new one.
  3311. :return: None
  3312. """
  3313. self.defaults.report_usage("on_edit_join()")
  3314. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3315. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3316. geo_type_set = set()
  3317. objs = self.collection.get_selected()
  3318. if len(objs) < 2:
  3319. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3320. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3321. return 'fail'
  3322. for obj in objs:
  3323. geo_type_set.add(obj.multigeo)
  3324. # if len(geo_type_list) == 1 means that all list elements are the same
  3325. if len(geo_type_set) != 1:
  3326. self.inform.emit('[ERROR] %s' %
  3327. _("Failed join. The Geometry objects are of different types.\n"
  3328. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3329. "convert from one to another and retry joining \n"
  3330. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3331. "the result may not be what was expected. \n"
  3332. "Check the generated GCODE."))
  3333. return
  3334. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3335. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3336. if True in geo_type_set:
  3337. def initialize(geo_obj, app):
  3338. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multi_geo=True, fuse_tools=fuse_tools)
  3339. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3340. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3341. for v in geo_obj.tools.values():
  3342. v['data']['name'] = obj_name_multi
  3343. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3344. else:
  3345. def initialize(geo_obj, app):
  3346. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multi_geo=False, fuse_tools=fuse_tools)
  3347. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3348. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3349. for v in geo_obj.tools.values():
  3350. v['data']['name'] = obj_name_single
  3351. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3352. self.should_we_save = True
  3353. def on_edit_join_exc(self):
  3354. """
  3355. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3356. a new Excellon.
  3357. :return: None
  3358. """
  3359. self.defaults.report_usage("on_edit_join_exc()")
  3360. objs = self.collection.get_selected()
  3361. for obj in objs:
  3362. if not isinstance(obj, ExcellonObject):
  3363. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3364. return
  3365. if len(objs) < 2:
  3366. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3367. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3368. return 'fail'
  3369. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3370. def initialize(exc_obj, app):
  3371. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3372. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3373. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3374. self.should_we_save = True
  3375. def on_edit_join_grb(self):
  3376. """
  3377. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3378. a new Gerber object.
  3379. :return: None
  3380. """
  3381. self.defaults.report_usage("on_edit_join_grb()")
  3382. objs = self.collection.get_selected()
  3383. for obj in objs:
  3384. if not isinstance(obj, GerberObject):
  3385. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3386. return
  3387. if len(objs) < 2:
  3388. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3389. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3390. return 'fail'
  3391. def initialize(grb_obj, app):
  3392. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3393. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3394. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3395. self.should_we_save = True
  3396. def on_convert_singlegeo_to_multigeo(self):
  3397. """
  3398. Called for converting a Geometry object from single-geo to multi-geo.
  3399. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3400. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3401. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3402. the solid-geometry of that tool.
  3403. :return: None
  3404. """
  3405. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3406. obj = self.collection.get_active()
  3407. if obj is None:
  3408. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3409. return
  3410. if not isinstance(obj, GeometryObject):
  3411. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3412. return
  3413. obj.multigeo = True
  3414. for tooluid, dict_value in obj.tools.items():
  3415. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3416. if not isinstance(obj.solid_geometry, list):
  3417. obj.solid_geometry = [obj.solid_geometry]
  3418. # obj.solid_geometry[:] = []
  3419. obj.plot()
  3420. self.should_we_save = True
  3421. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3422. def on_convert_multigeo_to_singlegeo(self):
  3423. """
  3424. Called for converting a Geometry object from multi-geo to single-geo.
  3425. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3426. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3427. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3428. the solid-geometry of that tool.
  3429. :return: None
  3430. """
  3431. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3432. obj = self.collection.get_active()
  3433. if obj is None:
  3434. self.inform.emit('[ERROR_NOTCL] %s' %
  3435. _("Failed. Select a Geometry Object and try again."))
  3436. return
  3437. if not isinstance(obj, GeometryObject):
  3438. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3439. (_("Expected a GeometryObject, got"), type(obj)))
  3440. return
  3441. obj.multigeo = False
  3442. total_solid_geometry = []
  3443. for tooluid, dict_value in obj.tools.items():
  3444. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3445. # clear the original geometry
  3446. dict_value['solid_geometry'][:] = []
  3447. obj.solid_geometry = deepcopy(total_solid_geometry)
  3448. obj.plot()
  3449. self.should_we_save = True
  3450. self.inform.emit('[success] %s' %
  3451. _("A Geometry object was converted to SingleGeo type."))
  3452. def on_defaults_dict_change(self, field):
  3453. """
  3454. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3455. Edit -> Preferences tab window.
  3456. :param field: the key of the self.defaults dictionary that was changed.
  3457. :return: None
  3458. """
  3459. self.preferencesUiManager.defaults_write_form_field(field=field)
  3460. if field == "units":
  3461. self.set_screen_units(self.defaults['units'])
  3462. def set_screen_units(self, units):
  3463. """
  3464. Set the FlatCAM units on the status bar.
  3465. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3466. :return: None
  3467. """
  3468. self.ui.units_label.setText("[" + units.lower() + "]")
  3469. def on_toggle_units_click(self):
  3470. try:
  3471. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3472. except (TypeError, AttributeError):
  3473. pass
  3474. if self.defaults["units"] == 'MM':
  3475. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3476. else:
  3477. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3478. self.on_toggle_units(no_pref=True)
  3479. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3480. lambda: self.on_toggle_units(no_pref=False))
  3481. def scale_defaults(self, sfactor, dimensions):
  3482. for dim in dimensions:
  3483. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3484. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3485. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3486. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3487. if not self.defaults[dim] or self.defaults[dim] == '':
  3488. continue
  3489. if isinstance(self.defaults[dim], str):
  3490. try:
  3491. tools_diameters = eval(self.defaults[dim])
  3492. except Exception as e:
  3493. self.log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3494. continue
  3495. elif isinstance(self.defaults[dim], (float, int)):
  3496. tools_diameters = [self.defaults[dim]]
  3497. else:
  3498. tools_diameters = list(self.defaults[dim])
  3499. if isinstance(tools_diameters, (tuple, list)):
  3500. pass
  3501. elif isinstance(tools_diameters, (int, float)):
  3502. tools_diameters = [self.defaults[dim]]
  3503. else:
  3504. continue
  3505. td_len = len(tools_diameters)
  3506. conv_list = []
  3507. for t in range(td_len):
  3508. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3509. self.defaults[dim] = conv_list
  3510. elif dim in ['global_gridx', 'global_gridy']:
  3511. # format the number of decimals to the one specified in self.decimals
  3512. try:
  3513. val = float(self.defaults[dim]) * sfactor
  3514. except Exception as e:
  3515. self.log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3516. continue
  3517. self.defaults[dim] = self.dec_format(val, self.decimals)
  3518. else:
  3519. # the number of decimals for the rest is kept unchanged
  3520. if self.defaults[dim]:
  3521. try:
  3522. val = float(self.defaults[dim]) * sfactor
  3523. except Exception as e:
  3524. self.log.debug(
  3525. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3526. )
  3527. continue
  3528. self.defaults[dim] = self.dec_format(val, self.decimals)
  3529. def on_toggle_units(self, no_pref=False):
  3530. """
  3531. Callback for the Units radio-button change in the Preferences tab.
  3532. Changes the application's default units adn for the project too.
  3533. If changing the project's units, the change propagates to all of
  3534. the objects in the project.
  3535. :return: None
  3536. """
  3537. self.defaults.report_usage("on_toggle_units")
  3538. if self.toggle_units_ignore:
  3539. return
  3540. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3541. # If option is the same, then ignore
  3542. if new_units == self.defaults["units"].upper():
  3543. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3544. return
  3545. # Keys in self.defaults for which to scale their values
  3546. dimensions = [
  3547. # Global
  3548. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3549. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3550. # Gerber Object
  3551. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3552. # Gerber Editor
  3553. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3554. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3555. # Excellon Object
  3556. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3557. # Excellon Editor
  3558. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3559. "excellon_editor_slot_length",
  3560. # Geometry Object
  3561. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3562. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3563. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3564. "geometry_extracut_length", "geometry_z_pdepth",
  3565. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3566. # CNCJob Object
  3567. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3568. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3569. # Isolation Tool
  3570. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3571. # Drilling Tool
  3572. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3573. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3574. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3575. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3576. # NCC Tool
  3577. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3578. "tools_ncc_newdia",
  3579. # Cutout Tool
  3580. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3581. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3582. # Paint Tool
  3583. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3584. # 2Sided Tool
  3585. "tools_2sided_drilldia",
  3586. # Film Tool
  3587. "tools_film_boundary", "tools_film_scale_stroke",
  3588. # Panel Tool
  3589. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3590. "tools_panelize_constrainy",
  3591. # Calculators Tool
  3592. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3593. # Transform Tool
  3594. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3595. "tools_transform_buffer_dis",
  3596. # SolderPaste Tool
  3597. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3598. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3599. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3600. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3601. # Corner Markers Tool
  3602. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3603. # Check Rules Tool
  3604. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3605. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3606. # QRCode Tool
  3607. "tools_qrcode_border_size",
  3608. # Copper Thieving Tool
  3609. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3610. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3611. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3612. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3613. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3614. "tools_copper_thieving_mask_clearance",
  3615. # Fiducials Tool
  3616. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3617. # Calibration Tool
  3618. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3619. # Drills Extraction Tool
  3620. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3621. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3622. # Punch Gerber Tool
  3623. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3624. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3625. # Invert Gerber Tool
  3626. "tools_invert_margin",
  3627. ]
  3628. # The scaling factor depending on choice of units.
  3629. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3630. # Changing project units. Warn user.
  3631. msgbox = QtWidgets.QMessageBox()
  3632. msgbox.setWindowTitle(_("Toggle Units"))
  3633. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3634. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3635. msgbox.setText(_("Changing the units of the project\n"
  3636. "will scale all objects.\n\n"
  3637. "Do you want to continue?"))
  3638. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3639. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3640. msgbox.setDefaultButton(bt_ok)
  3641. msgbox.exec_()
  3642. response = msgbox.clickedButton()
  3643. if response == bt_ok:
  3644. if no_pref is False:
  3645. self.preferencesUiManager.defaults_read_form()
  3646. self.scale_defaults(factor, dimensions)
  3647. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3648. self.defaults["units"] = new_units
  3649. # update the defaults from form, some may assume that the conversion is enough and it's not
  3650. self.on_options_app2project()
  3651. # update the objects
  3652. for obj in self.collection.get_list():
  3653. obj.convert_units(new_units)
  3654. # make that the properties stored in the object are also updated
  3655. self.app_obj.object_changed.emit(obj)
  3656. # rebuild the object UI
  3657. obj.build_ui()
  3658. # change this only if the workspace is active
  3659. if self.defaults['global_workspace'] is True:
  3660. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3661. # adjust the grid values on the main toolbar
  3662. val_x = float(self.defaults['global_gridx']) * factor
  3663. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3664. current = self.collection.get_active()
  3665. if current is not None:
  3666. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3667. if not isinstance(current, GeometryObject):
  3668. current.to_form()
  3669. # replot all objects
  3670. self.plot_all()
  3671. # set the status labels to reflect the current FlatCAM units
  3672. self.set_screen_units(new_units)
  3673. # signal to the app that we changed the object properties and it should save the project
  3674. self.should_we_save = True
  3675. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3676. else:
  3677. # Undo toggling
  3678. self.toggle_units_ignore = True
  3679. if self.defaults['units'].upper() == 'MM':
  3680. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3681. else:
  3682. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3683. self.toggle_units_ignore = False
  3684. # store the grid values so they are not changed in the next step
  3685. val_x = float(self.defaults['global_gridx'])
  3686. val_y = float(self.defaults['global_gridy'])
  3687. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3688. self.preferencesUiManager.defaults_read_form()
  3689. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3690. # in self.defaults from the GUI elements but
  3691. # I don't want it for the grid values, so I update them here
  3692. self.defaults['global_gridx'] = val_x
  3693. self.defaults['global_gridy'] = val_y
  3694. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3695. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3696. def on_deselect_all(self):
  3697. self.collection.set_all_inactive()
  3698. self.delete_selection_shape()
  3699. def on_workspace_modified(self):
  3700. # self.save_defaults(silent=True)
  3701. self.plotcanvas.delete_workspace()
  3702. self.preferencesUiManager.defaults_read_form()
  3703. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3704. def on_workspace(self):
  3705. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3706. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3707. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3708. else:
  3709. self.plotcanvas.delete_workspace()
  3710. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3711. self.preferencesUiManager.defaults_read_form()
  3712. # self.save_defaults(silent=True)
  3713. def on_workspace_toggle(self):
  3714. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3715. try:
  3716. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3717. except TypeError:
  3718. pass
  3719. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3720. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3721. self.on_workspace()
  3722. def on_cursor_type(self, val):
  3723. """
  3724. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3725. :return: None
  3726. """
  3727. self.app_cursor.enabled = False
  3728. if val == 'small':
  3729. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3730. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3731. self.app_cursor = self.plotcanvas.new_cursor()
  3732. else:
  3733. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3734. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3735. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3736. if self.ui.grid_snap_btn.isChecked():
  3737. self.app_cursor.enabled = True
  3738. else:
  3739. self.app_cursor.enabled = False
  3740. def on_tool_add_keypress(self):
  3741. # ## Current application units in Upper Case
  3742. self.units = self.defaults['units'].upper()
  3743. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3744. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3745. if notebook_widget_name == 'properties_tab':
  3746. if self.collection.get_active().kind == 'geometry':
  3747. # Tool add works for Geometry only if Advanced is True in Preferences
  3748. if self.defaults["global_app_level"] == 'a':
  3749. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3750. text='%s:' % _('Enter a Tool Diameter'),
  3751. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3752. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3753. tool_add_popup.wdg.selectAll()
  3754. val, ok = tool_add_popup.get_value()
  3755. if ok:
  3756. if float(val) == 0:
  3757. self.inform.emit('[WARNING_NOTCL] %s' %
  3758. _("Please enter a tool diameter with non-zero value, in Float format."))
  3759. return
  3760. self.collection.get_active().on_tool_add(clicked_state=False, dia=float(val))
  3761. else:
  3762. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3763. else:
  3764. msgbox = QtWidgets.QMessageBox()
  3765. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3766. "Go to Preferences -> General - Show Advanced Options."))
  3767. msgbox.setWindowTitle("Tool adding ...")
  3768. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3769. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3770. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3771. msgbox.setDefaultButton(bt_ok)
  3772. msgbox.exec_()
  3773. # work only if the notebook tab on focus is the Tools_Tab
  3774. if notebook_widget_name == 'tool_tab':
  3775. try:
  3776. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3777. except AttributeError:
  3778. return
  3779. # and only if the tool is NCC Tool
  3780. if tool_widget == self.ncclear_tool.toolName:
  3781. self.ncclear_tool.on_add_tool_by_key()
  3782. # and only if the tool is Paint Area Tool
  3783. elif tool_widget == self.paint_tool.toolName:
  3784. self.paint_tool.on_add_tool_by_key()
  3785. # and only if the tool is Solder Paste Dispensing Tool
  3786. elif tool_widget == self.paste_tool.toolName:
  3787. self.paste_tool.on_add_tool_by_key()
  3788. # and only if the tool is Isolation Tool
  3789. elif tool_widget == self.isolation_tool.toolName:
  3790. self.isolation_tool.on_add_tool_by_key()
  3791. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3792. # See description below.
  3793. def on_delete_keypress(self):
  3794. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3795. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3796. if notebook_widget_name == 'properties_tab':
  3797. if self.collection.get_active().kind == 'geometry':
  3798. self.collection.get_active().on_tool_delete()
  3799. # work only if the notebook tab on focus is the Tools_Tab
  3800. elif notebook_widget_name == 'tool_tab':
  3801. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3802. # and only if the tool is NCC Tool
  3803. if tool_widget == self.ncclear_tool.toolName:
  3804. self.ncclear_tool.on_tool_delete()
  3805. # and only if the tool is Paint Tool
  3806. elif tool_widget == self.paint_tool.toolName:
  3807. self.paint_tool.on_tool_delete()
  3808. # and only if the tool is Solder Paste Dispensing Tool
  3809. elif tool_widget == self.paste_tool.toolName:
  3810. self.paste_tool.on_tool_delete()
  3811. # and only if the tool is Isolation Tool
  3812. elif tool_widget == self.isolation_tool.toolName:
  3813. self.isolation_tool.on_tool_delete()
  3814. else:
  3815. self.on_delete()
  3816. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3817. # some screens you have to be careful where you hover with your mouse.
  3818. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3819. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3820. # Complicated, I know :)
  3821. def on_delete(self, force_deletion=False):
  3822. """
  3823. Delete the currently selected FlatCAMObjs.
  3824. :param force_deletion: used by Tcl command
  3825. :return: None
  3826. """
  3827. self.defaults.report_usage("on_delete()")
  3828. response = None
  3829. bt_ok = None
  3830. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3831. # a geometry object before we update it.
  3832. if self.call_source == 'app':
  3833. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3834. msgbox = QtWidgets.QMessageBox()
  3835. msgbox.setWindowTitle(_("Delete objects"))
  3836. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3837. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3838. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3839. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3840. "the selected objects?"))
  3841. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3842. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3843. msgbox.setDefaultButton(bt_ok)
  3844. msgbox.exec_()
  3845. response = msgbox.clickedButton()
  3846. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3847. response = bt_ok
  3848. if response == bt_ok:
  3849. if self.collection.get_active():
  3850. self.log.debug("App.on_delete()")
  3851. for obj_active in self.collection.get_selected():
  3852. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3853. if obj_active.kind == 'gerber':
  3854. obj_active.mark_shapes_storage.clear()
  3855. obj_active.mark_shapes.clear(update=True)
  3856. obj_active.mark_shapes.enabled = False
  3857. elif obj_active.kind == 'cncjob':
  3858. try:
  3859. obj_active.text_col.enabled = False
  3860. del obj_active.text_col
  3861. obj_active.annotation.clear(update=True)
  3862. del obj_active.annotation
  3863. obj_active.probing_shapes.clear(update=True)
  3864. except AttributeError as e:
  3865. self.log.debug(
  3866. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3867. )
  3868. while self.collection.get_selected():
  3869. self.delete_first_selected()
  3870. # make sure that the selection shape is deleted, too
  3871. self.delete_selection_shape()
  3872. # if there are no longer objects delete also the exclusion areas shapes
  3873. if not self.collection.get_list():
  3874. self.exc_areas.clear_shapes()
  3875. self.inform.emit('%s...' % _("Object(s) deleted"))
  3876. else:
  3877. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed."), _("No object is selected.")))
  3878. else:
  3879. self.inform.emit(_("Save the work in Editor and try again ..."))
  3880. def delete_first_selected(self):
  3881. # Keep this for later
  3882. try:
  3883. sel_obj = self.collection.get_active()
  3884. name = sel_obj.options["name"]
  3885. isPlotted = sel_obj.options["plot"]
  3886. except AttributeError:
  3887. self.log.debug("Nothing selected for deletion")
  3888. return
  3889. if self.is_legacy is True:
  3890. # Remove plot only if the object was plotted otherwise delaxes will fail
  3891. if isPlotted:
  3892. try:
  3893. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3894. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3895. except Exception as e:
  3896. self.log.debug("App.delete_first_selected() --> %s" % str(e))
  3897. self.plotcanvas.auto_adjust_axes()
  3898. # Remove from dictionary
  3899. self.collection.delete_active()
  3900. # Clear form
  3901. self.setup_default_properties_tab()
  3902. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3903. def on_set_origin(self):
  3904. """
  3905. Set the origin to the left mouse click position
  3906. :return: None
  3907. """
  3908. # display the message for the user
  3909. # and ask him to click on the desired position
  3910. self.defaults.report_usage("on_set_origin()")
  3911. def origin_replot():
  3912. def worker_task():
  3913. with self.proc_container.new('%s...' % _("Plotting")):
  3914. for obj in self.collection.get_list():
  3915. obj.plot()
  3916. self.plotcanvas.fit_view()
  3917. if self.is_legacy:
  3918. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3919. else:
  3920. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3921. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3922. self.inform.emit(_('Click to set the origin ...'))
  3923. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3924. # first disconnect it as it may have been used by something else
  3925. try:
  3926. self.replot_signal.disconnect()
  3927. except TypeError:
  3928. pass
  3929. self.replot_signal[list].connect(origin_replot)
  3930. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3931. """
  3932. :param event:
  3933. :param location:
  3934. :param noplot:
  3935. :param use_thread:
  3936. :return:
  3937. """
  3938. noplot_sig = noplot
  3939. def worker_task():
  3940. with self.proc_container.new(_("Setting Origin...")):
  3941. obj_list = self.collection.get_list()
  3942. for obj in obj_list:
  3943. obj.offset((x, y))
  3944. self.app_obj.object_changed.emit(obj)
  3945. # Update the object bounding box options
  3946. a, b, c, d = obj.bounds()
  3947. obj.options['xmin'] = a
  3948. obj.options['ymin'] = b
  3949. obj.options['xmax'] = c
  3950. obj.options['ymax'] = d
  3951. self.inform.emit('[success] %s...' % _('Origin set'))
  3952. for obj in obj_list:
  3953. out_name = obj.options["name"]
  3954. if obj.kind == 'gerber':
  3955. obj.source_file = self.f_handlers.export_gerber(
  3956. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3957. elif obj.kind == 'excellon':
  3958. obj.source_file = self.f_handlers.export_excellon(
  3959. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3960. if noplot_sig is False:
  3961. self.replot_signal.emit([])
  3962. if location is not None:
  3963. if len(location) != 2:
  3964. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3965. return 'fail'
  3966. x, y = location
  3967. if use_thread is True:
  3968. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3969. else:
  3970. worker_task()
  3971. self.should_we_save = True
  3972. return
  3973. if event is not None and event.button == 1:
  3974. if self.is_legacy is False:
  3975. event_pos = event.pos
  3976. else:
  3977. event_pos = (event.xdata, event.ydata)
  3978. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3979. if self.grid_status():
  3980. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3981. else:
  3982. pos = pos_canvas
  3983. x = 0 - pos[0]
  3984. y = 0 - pos[1]
  3985. if use_thread is True:
  3986. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3987. else:
  3988. worker_task()
  3989. self.should_we_save = True
  3990. def on_move2origin(self, use_thread=True):
  3991. """
  3992. Move selected objects to origin.
  3993. :param use_thread: Control if to use threaded operation. Boolean.
  3994. :return:
  3995. """
  3996. def worker_task():
  3997. with self.proc_container.new(_("Moving to Origin...")):
  3998. obj_list = self.collection.get_selected()
  3999. if not obj_list:
  4000. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4001. return
  4002. xminlist = []
  4003. yminlist = []
  4004. # first get a bounding box to fit all
  4005. for obj in obj_list:
  4006. xmin, ymin, xmax, ymax = obj.bounds()
  4007. xminlist.append(xmin)
  4008. yminlist.append(ymin)
  4009. # get the minimum x,y for all objects selected
  4010. x = min(xminlist)
  4011. y = min(yminlist)
  4012. for obj in obj_list:
  4013. obj.offset((-x, -y))
  4014. self.app_obj.object_changed.emit(obj)
  4015. # Update the object bounding box options
  4016. a, b, c, d = obj.bounds()
  4017. obj.options['xmin'] = a
  4018. obj.options['ymin'] = b
  4019. obj.options['xmax'] = c
  4020. obj.options['ymax'] = d
  4021. for obj in obj_list:
  4022. obj.plot()
  4023. for obj in obj_list:
  4024. out_name = obj.options["name"]
  4025. if obj.kind == 'gerber':
  4026. obj.source_file = self.f_handlers.export_gerber(
  4027. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4028. elif obj.kind == 'excellon':
  4029. obj.source_file = self.f_handlers.export_excellon(
  4030. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4031. self.inform.emit('[success] %s...' % _('Origin set'))
  4032. if use_thread is True:
  4033. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4034. else:
  4035. worker_task()
  4036. self.should_we_save = True
  4037. def on_jump_to(self, custom_location=None, fit_center=True):
  4038. """
  4039. Jump to a location by setting the mouse cursor location.
  4040. :param custom_location: Jump to a specified point. (x, y) tuple.
  4041. :param fit_center: If to fit view. Boolean.
  4042. :return:
  4043. """
  4044. self.defaults.report_usage("on_jump_to()")
  4045. if not custom_location:
  4046. dia_box_location = None
  4047. try:
  4048. dia_box_location = eval(self.clipboard.text())
  4049. except Exception:
  4050. pass
  4051. if type(dia_box_location) == tuple:
  4052. dia_box_location = str(dia_box_location)
  4053. else:
  4054. dia_box_location = None
  4055. # dia_box = Dialog_box(title=_("Jump to ..."),
  4056. # label=_("Enter the coordinates in format X,Y:"),
  4057. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4058. # initial_text=dia_box_location)
  4059. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4060. label=_("Enter the coordinates in format X,Y:"),
  4061. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4062. initial_text=dia_box_location,
  4063. reference=self.defaults['global_jump_ref'])
  4064. if dia_box.ok is True:
  4065. try:
  4066. location = eval(dia_box.location)
  4067. if not isinstance(location, tuple):
  4068. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4069. return
  4070. if dia_box.reference == 'rel':
  4071. rel_x = self.mouse[0] + location[0]
  4072. rel_y = self.mouse[1] + location[1]
  4073. location = (rel_x, rel_y)
  4074. self.defaults['global_jump_ref'] = dia_box.reference
  4075. except Exception:
  4076. return
  4077. else:
  4078. return
  4079. else:
  4080. location = custom_location
  4081. self.jump_signal.emit(location)
  4082. if fit_center:
  4083. self.plotcanvas.fit_center(loc=location)
  4084. cursor = QtGui.QCursor()
  4085. if self.is_legacy is False:
  4086. # I don't know where those differences come from but they are constant for the current
  4087. # execution of the application and they are multiples of a value around 0.0263mm.
  4088. # In a random way sometimes they are more sometimes they are less
  4089. # if units == 'MM':
  4090. # cal_factor = 0.0263
  4091. # else:
  4092. # cal_factor = 0.0263 / 25.4
  4093. cal_location = (location[0], location[1])
  4094. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4095. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4096. j_pos = (
  4097. int(canvas_origin.x() + round(jump_loc[0])),
  4098. int(canvas_origin.y() + round(jump_loc[1]))
  4099. )
  4100. cursor.setPos(j_pos[0], j_pos[1])
  4101. else:
  4102. # find the canvas origin which is in the top left corner
  4103. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4104. # determine the coordinates for the lowest left point of the canvas
  4105. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4106. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4107. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4108. # canvas) and the point (width, height) is in the top-right location
  4109. loc = self.plotcanvas.axes.transData.transform_point(location)
  4110. j_pos = (
  4111. int(x0 + loc[0]),
  4112. int(y0 - loc[1])
  4113. )
  4114. cursor.setPos(j_pos[0], j_pos[1])
  4115. self.plotcanvas.mouse = [location[0], location[1]]
  4116. if self.defaults["global_cursor_color_enabled"] is True:
  4117. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4118. else:
  4119. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4120. if self.grid_status():
  4121. # Update cursor
  4122. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4123. symbol='++', edge_color=self.cursor_color_3D,
  4124. edge_width=self.defaults["global_cursor_width"],
  4125. size=self.defaults["global_cursor_size"])
  4126. # Set the relative position label
  4127. dx = location[0] - float(self.rel_point1[0])
  4128. dy = location[1] - float(self.rel_point1[1])
  4129. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4130. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4131. # Set the position label
  4132. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4133. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4134. units = self.defaults["units"].lower()
  4135. self.plotcanvas.text_hud.text = \
  4136. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4137. dx, units, dy, units, location[0], units, location[1], units)
  4138. self.inform.emit('[success] %s' % _("Done."))
  4139. return location
  4140. def on_locate(self, obj, fit_center=True):
  4141. """
  4142. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4143. :param obj: The object on which to locate certain points
  4144. :param fit_center: If to fit view. Boolean.
  4145. :return: A point location. (x, y) tuple.
  4146. """
  4147. self.defaults.report_usage("on_locate()")
  4148. if obj is None:
  4149. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4150. return 'fail'
  4151. class DialogBoxChoice(QtWidgets.QDialog):
  4152. def __init__(self, title=None, icon=None, choice='bl'):
  4153. """
  4154. :param title: string with the window title
  4155. """
  4156. super(DialogBoxChoice, self).__init__()
  4157. self.ok = False
  4158. self.setWindowIcon(icon)
  4159. self.setWindowTitle(str(title))
  4160. self.form = QtWidgets.QFormLayout(self)
  4161. self.ref_radio = RadioSet([
  4162. {"label": _("Bottom Left"), "value": "bl"},
  4163. {"label": _("Top Left"), "value": "tl"},
  4164. {"label": _("Bottom Right"), "value": "br"},
  4165. {"label": _("Top Right"), "value": "tr"},
  4166. {"label": _("Center"), "value": "c"}
  4167. ], orientation='vertical', stretch=False)
  4168. self.ref_radio.set_value(choice)
  4169. self.form.addRow(self.ref_radio)
  4170. self.button_box = QtWidgets.QDialogButtonBox(
  4171. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4172. Qt.Horizontal, parent=self)
  4173. self.form.addRow(self.button_box)
  4174. self.button_box.accepted.connect(self.accept)
  4175. self.button_box.rejected.connect(self.reject)
  4176. if self.exec_() == QtWidgets.QDialog.Accepted:
  4177. self.ok = True
  4178. self.location_point = self.ref_radio.get_value()
  4179. else:
  4180. self.ok = False
  4181. self.location_point = None
  4182. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4183. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4184. choice=self.defaults['global_locate_pt'])
  4185. if dia_box.ok is True:
  4186. try:
  4187. location_point = dia_box.location_point
  4188. self.defaults['global_locate_pt'] = dia_box.location_point
  4189. except Exception:
  4190. return
  4191. else:
  4192. return
  4193. loc_b = obj.bounds()
  4194. if location_point == 'bl':
  4195. location = (loc_b[0], loc_b[1])
  4196. elif location_point == 'tl':
  4197. location = (loc_b[0], loc_b[3])
  4198. elif location_point == 'br':
  4199. location = (loc_b[2], loc_b[1])
  4200. elif location_point == 'tr':
  4201. location = (loc_b[2], loc_b[3])
  4202. else:
  4203. # center
  4204. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4205. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4206. location = (cx, cy)
  4207. self.locate_signal.emit(location, location_point)
  4208. if fit_center:
  4209. self.plotcanvas.fit_center(loc=location)
  4210. cursor = QtGui.QCursor()
  4211. if self.is_legacy is False:
  4212. # I don't know where those differences come from but they are constant for the current
  4213. # execution of the application and they are multiples of a value around 0.0263mm.
  4214. # In a random way sometimes they are more sometimes they are less
  4215. # if units == 'MM':
  4216. # cal_factor = 0.0263
  4217. # else:
  4218. # cal_factor = 0.0263 / 25.4
  4219. cal_location = (location[0], location[1])
  4220. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4221. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4222. j_pos = (
  4223. int(canvas_origin.x() + round(jump_loc[0])),
  4224. int(canvas_origin.y() + round(jump_loc[1]))
  4225. )
  4226. cursor.setPos(j_pos[0], j_pos[1])
  4227. else:
  4228. # find the canvas origin which is in the top left corner
  4229. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4230. # determine the coordinates for the lowest left point of the canvas
  4231. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4232. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4233. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4234. # canvas) and the point (width, height) is in the top-right location
  4235. loc = self.plotcanvas.axes.transData.transform_point(location)
  4236. j_pos = (
  4237. int(x0 + loc[0]),
  4238. int(y0 - loc[1])
  4239. )
  4240. cursor.setPos(j_pos[0], j_pos[1])
  4241. self.plotcanvas.mouse = [location[0], location[1]]
  4242. if self.defaults["global_cursor_color_enabled"] is True:
  4243. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4244. else:
  4245. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4246. if self.grid_status():
  4247. # Update cursor
  4248. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4249. symbol='++', edge_color=self.cursor_color_3D,
  4250. edge_width=self.defaults["global_cursor_width"],
  4251. size=self.defaults["global_cursor_size"])
  4252. # Set the relative position label
  4253. self.dx = location[0] - float(self.rel_point1[0])
  4254. self.dy = location[1] - float(self.rel_point1[1])
  4255. # Set the position label
  4256. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4257. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4258. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4259. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4260. units = self.defaults["units"].lower()
  4261. self.plotcanvas.text_hud.text = \
  4262. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4263. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4264. self.inform.emit('[success] %s' % _("Done."))
  4265. return location
  4266. def on_copy_command(self):
  4267. """
  4268. Will copy a selection of objects, creating new objects.
  4269. :return:
  4270. """
  4271. self.defaults.report_usage("on_copy_command()")
  4272. def initialize(obj_init, app_obj):
  4273. """
  4274. :param obj_init: the new object
  4275. :type obj_init: class
  4276. :param app_obj: An instance of the App class
  4277. :type app_obj: App
  4278. :return: None
  4279. :rtype:
  4280. """
  4281. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4282. try:
  4283. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4284. except AttributeError:
  4285. pass
  4286. try:
  4287. obj_init.apertures = deepcopy(obj.apertures)
  4288. except AttributeError:
  4289. pass
  4290. try:
  4291. if obj.tools:
  4292. obj_init.tools = deepcopy(obj.tools)
  4293. except Exception as err:
  4294. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4295. try:
  4296. obj_init.source_file = deepcopy(obj.source_file)
  4297. except (AttributeError, TypeError):
  4298. pass
  4299. def initialize_excellon(obj_init, app_obj):
  4300. obj_init.source_file = deepcopy(obj.source_file)
  4301. obj_init.tools = deepcopy(obj.tools)
  4302. # drills are offset, so they need to be deep copied
  4303. obj_init.drills = deepcopy(obj.drills)
  4304. # slots are offset, so they need to be deep copied
  4305. obj_init.slots = deepcopy(obj.slots)
  4306. obj_init.create_geometry()
  4307. if not obj_init.tools:
  4308. app_obj.debug("on_copy_command() --> no excellon tools")
  4309. return 'fail'
  4310. def initialize_script(obj_init, app_obj):
  4311. obj_init.source_file = deepcopy(obj.source_file)
  4312. def initialize_document(obj_init, app_obj):
  4313. obj_init.source_file = deepcopy(obj.source_file)
  4314. for obj in self.collection.get_selected():
  4315. obj_name = obj.options["name"]
  4316. try:
  4317. if isinstance(obj, ExcellonObject):
  4318. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4319. elif isinstance(obj, GerberObject):
  4320. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4321. elif isinstance(obj, GeometryObject):
  4322. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4323. elif isinstance(obj, ScriptObject):
  4324. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4325. elif isinstance(obj, DocumentObject):
  4326. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4327. except Exception as e:
  4328. return "Operation failed: %s" % str(e)
  4329. def on_copy_object2(self, custom_name):
  4330. def initialize_geometry(obj_init, app_obj):
  4331. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4332. try:
  4333. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4334. except AttributeError:
  4335. pass
  4336. try:
  4337. obj_init.apertures = deepcopy(obj.apertures)
  4338. except AttributeError:
  4339. pass
  4340. try:
  4341. if obj.tools:
  4342. obj_init.tools = deepcopy(obj.tools)
  4343. except Exception as ee:
  4344. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4345. def initialize_gerber(obj_init, app_obj):
  4346. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4347. obj_init.apertures = deepcopy(obj.apertures)
  4348. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4349. if not obj_init.apertures:
  4350. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4351. return 'fail'
  4352. def initialize_excellon(obj_init, app_obj):
  4353. obj_init.tools = deepcopy(obj.tools)
  4354. # drills are offset, so they need to be deep copied
  4355. obj_init.drills = deepcopy(obj.drills)
  4356. # slots are offset, so they need to be deep copied
  4357. obj_init.slots = deepcopy(obj.slots)
  4358. obj_init.create_geometry()
  4359. if not obj_init.tools:
  4360. app_obj.debug("on_copy_object2() --> no excellon tools")
  4361. return 'fail'
  4362. for obj in self.collection.get_selected():
  4363. obj_name = obj.options["name"]
  4364. try:
  4365. if isinstance(obj, ExcellonObject):
  4366. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4367. elif isinstance(obj, GerberObject):
  4368. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4369. elif isinstance(obj, GeometryObject):
  4370. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4371. except Exception as er:
  4372. return "Operation failed: %s" % str(er)
  4373. def on_rename_object(self, text):
  4374. """
  4375. Will rename an object.
  4376. :param text: New name for the object.
  4377. :return:
  4378. """
  4379. self.defaults.report_usage("on_rename_object()")
  4380. named_obj = self.collection.get_active()
  4381. for obj in named_obj:
  4382. if obj is list:
  4383. self.on_rename_object(text)
  4384. else:
  4385. try:
  4386. obj.options['name'] = text
  4387. except Exception as e:
  4388. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4389. def convert_any2geo(self):
  4390. """
  4391. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4392. :return:
  4393. """
  4394. self.defaults.report_usage("convert_any2geo()")
  4395. def initialize(obj_init, app):
  4396. obj_init.solid_geometry = obj.solid_geometry
  4397. try:
  4398. obj_init.follow_geometry = obj.follow_geometry
  4399. except AttributeError:
  4400. pass
  4401. try:
  4402. obj_init.apertures = obj.apertures
  4403. except AttributeError:
  4404. pass
  4405. try:
  4406. if obj.tools:
  4407. obj_init.tools = obj.tools
  4408. except AttributeError:
  4409. pass
  4410. def initialize_excellon(obj_init, app_obj):
  4411. # objs = self.collection.get_selected()
  4412. # GeometryObject.merge(objs, obj)
  4413. solid_geo = []
  4414. for tool in obj.tools:
  4415. for geo in obj.tools[tool]['solid_geometry']:
  4416. solid_geo.append(geo)
  4417. obj_init.solid_geometry = deepcopy(solid_geo)
  4418. if not obj_init.solid_geometry:
  4419. app_obj.log("convert_any2geo() failed")
  4420. return 'fail'
  4421. if not self.collection.get_selected():
  4422. log.warning("App.convert_any2geo --> No object selected")
  4423. self.inform.emit('[WARNING_NOTCL] %s' %
  4424. _("No object is selected."))
  4425. return
  4426. for obj in self.collection.get_selected():
  4427. obj_name = obj.options["name"]
  4428. try:
  4429. if obj.kind == 'excellon':
  4430. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4431. else:
  4432. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4433. except Exception as e:
  4434. return "Operation failed: %s" % str(e)
  4435. def convert_any2gerber(self):
  4436. """
  4437. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4438. :return:
  4439. """
  4440. def initialize_geometry(obj_init, app_obj):
  4441. apertures = {}
  4442. apid = 0
  4443. apertures[str(apid)] = {}
  4444. apertures[str(apid)]['geometry'] = []
  4445. for obj_orig in obj.solid_geometry:
  4446. new_elem = {'solid': obj_orig}
  4447. try:
  4448. new_elem['follow'] = obj_orig.exterior
  4449. except AttributeError:
  4450. pass
  4451. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4452. apertures[str(apid)]['size'] = 0.0
  4453. apertures[str(apid)]['type'] = 'C'
  4454. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4455. obj_init.apertures = deepcopy(apertures)
  4456. if not obj_init.apertures:
  4457. app_obj.log("convert_any2gerber() failed")
  4458. return 'fail'
  4459. def initialize_excellon(obj_init, app_obj):
  4460. apertures = {}
  4461. apid = 10
  4462. for tool in obj.tools:
  4463. apertures[str(apid)] = {}
  4464. apertures[str(apid)]['geometry'] = []
  4465. for geo in obj.tools[tool]['solid_geometry']:
  4466. new_el = {'solid': geo, 'follow': geo.exterior}
  4467. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4468. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4469. apertures[str(apid)]['type'] = 'C'
  4470. apid += 1
  4471. # create solid_geometry
  4472. solid_geometry = []
  4473. for apid in apertures:
  4474. for geo_el in apertures[apid]['geometry']:
  4475. solid_geometry.append(geo_el['solid'])
  4476. solid_geometry = MultiPolygon(solid_geometry)
  4477. solid_geometry = solid_geometry.buffer(0.0000001)
  4478. obj_init.solid_geometry = deepcopy(solid_geometry)
  4479. obj_init.apertures = deepcopy(apertures)
  4480. if not obj_init.apertures:
  4481. app_obj.log("convert_any2gerber() failed")
  4482. return 'fail'
  4483. if not self.collection.get_selected():
  4484. log.warning("App.convert_any2gerber --> No object selected")
  4485. self.inform.emit('[WARNING_NOTCL] %s' %
  4486. _("No object is selected."))
  4487. return
  4488. for obj in self.collection.get_selected():
  4489. obj_name = obj.options["name"]
  4490. try:
  4491. if obj.kind == 'excellon':
  4492. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4493. elif obj.kind == 'geometry':
  4494. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4495. else:
  4496. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4497. except Exception as e:
  4498. return "Operation failed: %s" % str(e)
  4499. def convert_any2excellon(self):
  4500. """
  4501. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4502. :return:
  4503. """
  4504. def initialize_geometry(obj_init, app_obj):
  4505. tools = {}
  4506. tooluid = 1
  4507. obj_init.solid_geometry = []
  4508. for geo in obj.solid_geometry:
  4509. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4510. continue
  4511. minx, miny, maxx, maxy = geo.bounds
  4512. new_dia = min([maxx-minx, maxy-miny])
  4513. new_drill = geo.centroid
  4514. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4515. current_tooldias = []
  4516. if tools:
  4517. for tool in tools:
  4518. if tools[tool] and 'tooldia' in tools[tool]:
  4519. current_tooldias.append(tools[tool]['tooldia'])
  4520. if new_dia in current_tooldias:
  4521. digits = app_obj.decimals
  4522. for tool in tools:
  4523. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4524. tools[tool]['drills'].append(new_drill)
  4525. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4526. else:
  4527. tools[tooluid] = {}
  4528. tools[tooluid]['tooldia'] = new_dia
  4529. tools[tooluid]['drills'] = [new_drill]
  4530. tools[tooluid]['slots'] = []
  4531. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4532. tooluid += 1
  4533. try:
  4534. obj_init.solid_geometry.append(new_drill_geo)
  4535. except (TypeError, AttributeError):
  4536. obj_init.solid_geometry = [new_drill_geo]
  4537. obj_init.tools = deepcopy(tools)
  4538. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4539. if not obj_init.solid_geometry:
  4540. return 'fail'
  4541. def initialize_gerber(obj_init, app_obj):
  4542. tools = {}
  4543. tooluid = 1
  4544. digits = app_obj.decimals
  4545. obj_init.solid_geometry = []
  4546. for apid in obj.apertures:
  4547. if 'geometry' in obj.apertures[apid]:
  4548. for geo_dict in obj.apertures[apid]['geometry']:
  4549. if 'follow' in geo_dict:
  4550. if isinstance(geo_dict['follow'], Point):
  4551. geo = geo_dict['solid']
  4552. minx, miny, maxx, maxy = geo.bounds
  4553. new_dia = min([maxx - minx, maxy - miny])
  4554. new_drill = geo.centroid
  4555. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4556. current_tooldias = []
  4557. if tools:
  4558. for tool in tools:
  4559. if tools[tool] and 'tooldia' in tools[tool]:
  4560. current_tooldias.append(
  4561. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4562. )
  4563. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4564. if formatted_new_dia in current_tooldias:
  4565. for tool in tools:
  4566. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4567. if new_drill not in tools[tool]['drills']:
  4568. tools[tool]['drills'].append(new_drill)
  4569. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4570. else:
  4571. tools[tooluid] = {}
  4572. tools[tooluid]['tooldia'] = new_dia
  4573. tools[tooluid]['drills'] = [new_drill]
  4574. tools[tooluid]['slots'] = []
  4575. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4576. tooluid += 1
  4577. try:
  4578. obj_init.solid_geometry.append(new_drill_geo)
  4579. except (TypeError, AttributeError):
  4580. obj_init.solid_geometry = [new_drill_geo]
  4581. elif isinstance(geo_dict['follow'], LineString):
  4582. geo_coords = list(geo_dict['follow'].coords)
  4583. # slots can have only a start and stop point and no intermediate points
  4584. if len(geo_coords) != 2:
  4585. continue
  4586. geo = geo_dict['solid']
  4587. try:
  4588. new_dia = obj.apertures[apid]['size']
  4589. except Exception:
  4590. continue
  4591. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4592. new_slot_geo = geo
  4593. current_tooldias = []
  4594. if tools:
  4595. for tool in tools:
  4596. if tools[tool] and 'tooldia' in tools[tool]:
  4597. current_tooldias.append(
  4598. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4599. )
  4600. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4601. for tool in tools:
  4602. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4603. '%.*f' % (self.decimals, new_dia)):
  4604. if new_slot not in tools[tool]['slots']:
  4605. tools[tool]['slots'].append(new_slot)
  4606. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4607. else:
  4608. tools[tooluid] = {}
  4609. tools[tooluid]['tooldia'] = new_dia
  4610. tools[tooluid]['drills'] = []
  4611. tools[tooluid]['slots'] = [new_slot]
  4612. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4613. tooluid += 1
  4614. try:
  4615. obj_init.solid_geometry.append(new_slot_geo)
  4616. except (TypeError, AttributeError):
  4617. obj_init.solid_geometry = [new_slot_geo]
  4618. obj_init.tools = deepcopy(tools)
  4619. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4620. if not obj_init.solid_geometry:
  4621. return 'fail'
  4622. if not self.collection.get_selected():
  4623. log.warning("App.convert_any2excellon--> No object selected")
  4624. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4625. return
  4626. for obj in self.collection.get_selected():
  4627. obj_name = obj.options["name"]
  4628. try:
  4629. if obj.kind == 'gerber':
  4630. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4631. elif obj.kind == 'geometry':
  4632. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4633. else:
  4634. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4635. except Exception as e:
  4636. return "Operation failed: %s" % str(e)
  4637. def abort_all_tasks(self):
  4638. """
  4639. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4640. on the first possible occasion.
  4641. :return:
  4642. """
  4643. if self.abort_flag is False:
  4644. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4645. self.abort_flag = True
  4646. self.cleanup.emit()
  4647. def app_is_idle(self):
  4648. if self.abort_flag:
  4649. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4650. self.abort_flag = False
  4651. def on_selectall(self):
  4652. """
  4653. Will draw a selection box shape around the selected objects.
  4654. :return:
  4655. """
  4656. self.defaults.report_usage("on_selectall()")
  4657. # delete the possible selection box around a possible selected object
  4658. self.delete_selection_shape()
  4659. for name in self.collection.get_names():
  4660. self.collection.set_active(name)
  4661. curr_sel_obj = self.collection.get_by_name(name)
  4662. # create the selection box around the selected object
  4663. if self.defaults['global_selection_shape'] is True:
  4664. self.draw_selection_shape(curr_sel_obj)
  4665. def on_toggle_preferences(self):
  4666. pref_open = False
  4667. for idx in range(self.ui.plot_tab_area.count()):
  4668. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4669. pref_open = True
  4670. if pref_open:
  4671. for idx in range(self.ui.plot_tab_area.count()):
  4672. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4673. self.ui.plot_tab_area.removeTab(idx)
  4674. break
  4675. self.ui.pref_status_label.setStyleSheet("")
  4676. else:
  4677. self.on_preferences()
  4678. def on_preferences(self):
  4679. """
  4680. Adds the Preferences in a Tab in Plot Area
  4681. :return:
  4682. """
  4683. # add the tab if it was closed
  4684. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4685. # delete the absolute and relative position and messages in the infobar
  4686. # self.ui.position_label.setText("")
  4687. # self.ui.rel_position_label.setText("")
  4688. # hide coordinates toolbars in the infobar while in DB
  4689. self.ui.coords_toolbar.hide()
  4690. self.ui.delta_coords_toolbar.hide()
  4691. # Switch plot_area to preferences page
  4692. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4693. # self.ui.show()
  4694. self.ui.pref_status_label.setStyleSheet("""
  4695. QLabel
  4696. {
  4697. color: black;
  4698. background-color: lightseagreen;
  4699. }
  4700. """
  4701. )
  4702. # detect changes in the preferences
  4703. for idx in range(self.ui.pref_tab_area.count()):
  4704. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4705. try:
  4706. try:
  4707. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4708. except (TypeError, AttributeError):
  4709. pass
  4710. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4711. except AttributeError:
  4712. pass
  4713. try:
  4714. try:
  4715. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4716. except (TypeError, AttributeError):
  4717. pass
  4718. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4719. except AttributeError:
  4720. pass
  4721. try:
  4722. try:
  4723. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4724. except (TypeError, AttributeError):
  4725. pass
  4726. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4727. except AttributeError:
  4728. pass
  4729. try:
  4730. try:
  4731. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4732. except (TypeError, AttributeError):
  4733. pass
  4734. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4735. except AttributeError:
  4736. pass
  4737. try:
  4738. try:
  4739. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4740. except (TypeError, AttributeError):
  4741. pass
  4742. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4743. except AttributeError:
  4744. pass
  4745. def on_tools_database(self, source='app'):
  4746. """
  4747. Adds the Tools Database in a Tab in Plot Area.
  4748. :return:
  4749. """
  4750. filename = self.tools_database_path()
  4751. # load the database tools from the file
  4752. try:
  4753. with open(filename) as f:
  4754. __ = f.read()
  4755. except Exception as eros:
  4756. self.log.debug("The tools DB file is not loaded: %s" % str(eros))
  4757. log.error("Could not access tools DB file. The file may be locked,\n"
  4758. "not existing or doesn't have the read permissions.\n"
  4759. "Check to see if exists, it should be here: %s\n"
  4760. "It may help to reboot the app, it will try to recreate it if it's missing." % self.data_path)
  4761. self.inform.emit('[ERROR] %s' % _("Could not load the file."))
  4762. return 'fail'
  4763. for idx in range(self.ui.plot_tab_area.count()):
  4764. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4765. # there can be only one instance of Tools Database at one time
  4766. return
  4767. if source == 'app':
  4768. self.tools_db_tab = ToolsDB2(
  4769. app=self,
  4770. parent=self.ui,
  4771. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4772. )
  4773. elif source == 'ncc':
  4774. self.tools_db_tab = ToolsDB2(
  4775. app=self,
  4776. parent=self.ui,
  4777. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4778. )
  4779. elif source == 'paint':
  4780. self.tools_db_tab = ToolsDB2(
  4781. app=self,
  4782. parent=self.ui,
  4783. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4784. )
  4785. elif source == 'iso':
  4786. self.tools_db_tab = ToolsDB2(
  4787. app=self,
  4788. parent=self.ui,
  4789. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4790. )
  4791. elif source == 'cutout':
  4792. self.tools_db_tab = ToolsDB2(
  4793. app=self,
  4794. parent=self.ui,
  4795. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4796. )
  4797. # add the tab if it was closed
  4798. try:
  4799. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4800. self.tools_db_tab.setObjectName("database_tab")
  4801. except Exception as e:
  4802. self.log.debug("App.on_tools_database() --> %s" % str(e))
  4803. return
  4804. # delete the absolute and relative position and messages in the infobar
  4805. # self.ui.position_label.setText("")
  4806. # self.ui.rel_position_label.setText("")
  4807. # hide coordinates toolbars in the infobar while in DB
  4808. self.ui.coords_toolbar.hide()
  4809. self.ui.delta_coords_toolbar.hide()
  4810. # Switch plot_area to preferences page
  4811. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4812. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4813. self.tools_db_tab.ui_connect()
  4814. def on_geometry_tool_add_from_db_executed(self, tool):
  4815. """
  4816. Here add the tool from DB in the selected geometry object.
  4817. :return:
  4818. """
  4819. tool_from_db = deepcopy(tool)
  4820. obj = self.collection.get_active()
  4821. if obj.kind == 'geometry':
  4822. if tool['data']['tool_target'] not in [0, 1]: # General, Milling Type
  4823. # close the tab and delete it
  4824. for idx in range(self.ui.plot_tab_area.count()):
  4825. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4826. wdg = self.ui.plot_tab_area.widget(idx)
  4827. wdg.deleteLater()
  4828. self.ui.plot_tab_area.removeTab(idx)
  4829. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4830. return
  4831. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4832. # close the tab and delete it
  4833. for idx in range(self.ui.plot_tab_area.count()):
  4834. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4835. wdg = self.ui.plot_tab_area.widget(idx)
  4836. wdg.deleteLater()
  4837. self.ui.plot_tab_area.removeTab(idx)
  4838. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4839. elif obj.kind == 'gerber':
  4840. if tool['data']['tool_target'] not in [0, 3]: # General, Isolation Type
  4841. # close the tab and delete it
  4842. for idx in range(self.ui.plot_tab_area.count()):
  4843. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4844. wdg = self.ui.plot_tab_area.widget(idx)
  4845. wdg.deleteLater()
  4846. self.ui.plot_tab_area.removeTab(idx)
  4847. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4848. return
  4849. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4850. # close the tab and delete it
  4851. for idx in range(self.ui.plot_tab_area.count()):
  4852. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4853. wdg = self.ui.plot_tab_area.widget(idx)
  4854. wdg.deleteLater()
  4855. self.ui.plot_tab_area.removeTab(idx)
  4856. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4857. else:
  4858. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4859. def on_plot_area_tab_closed(self, tab_obj_name):
  4860. """
  4861. Executed whenever a QTab is closed in the Plot Area.
  4862. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4863. :return:
  4864. """
  4865. if tab_obj_name == "preferences_tab":
  4866. self.preferencesUiManager.on_close_preferences_tab()
  4867. elif tab_obj_name == "database_tab":
  4868. # disconnect the signals from the table widget in tab
  4869. self.tools_db_tab.ui_disconnect()
  4870. if self.tools_db_changed_flag is True:
  4871. msgbox = QtWidgets.QMessageBox()
  4872. msgbox.setText(_("One or more Tools are edited.\n"
  4873. "Do you want to update the Tools Database?"))
  4874. msgbox.setWindowTitle(_("Save Tools Database"))
  4875. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4876. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4877. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4878. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4879. msgbox.setDefaultButton(bt_yes)
  4880. msgbox.exec_()
  4881. response = msgbox.clickedButton()
  4882. if response == bt_yes:
  4883. self.tools_db_tab.on_save_tools_db()
  4884. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4885. else:
  4886. self.tools_db_changed_flag = False
  4887. self.inform.emit('')
  4888. return
  4889. self.tools_db_tab.deleteLater()
  4890. elif tab_obj_name == "text_editor_tab":
  4891. self.toggle_codeeditor = False
  4892. elif tab_obj_name == "bookmarks_tab":
  4893. self.book_dialog_tab.rebuild_actions()
  4894. self.book_dialog_tab.deleteLater()
  4895. else:
  4896. pass
  4897. # restore the coords toolbars
  4898. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4899. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4900. def on_flipy(self):
  4901. """
  4902. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4903. :return:
  4904. """
  4905. self.defaults.report_usage("on_flipy()")
  4906. obj_list = self.collection.get_selected()
  4907. xminlist = []
  4908. yminlist = []
  4909. xmaxlist = []
  4910. ymaxlist = []
  4911. if not obj_list:
  4912. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4913. else:
  4914. try:
  4915. # first get a bounding box to fit all
  4916. for obj in obj_list:
  4917. xmin, ymin, xmax, ymax = obj.bounds()
  4918. xminlist.append(xmin)
  4919. yminlist.append(ymin)
  4920. xmaxlist.append(xmax)
  4921. ymaxlist.append(ymax)
  4922. # get the minimum x,y and maximum x,y for all objects selected
  4923. xminimal = min(xminlist)
  4924. yminimal = min(yminlist)
  4925. xmaximal = max(xmaxlist)
  4926. ymaximal = max(ymaxlist)
  4927. px = 0.5 * (xminimal + xmaximal)
  4928. py = 0.5 * (yminimal + ymaximal)
  4929. # execute mirroring
  4930. for obj in obj_list:
  4931. obj.mirror('X', [px, py])
  4932. obj.plot()
  4933. self.app_obj.object_changed.emit(obj)
  4934. self.inform.emit('[success] %s.' % _("Flip on Y axis done"))
  4935. except Exception as e:
  4936. self.app.inform.emit('[ERROR_NOTCL] %s: %s.' % (_("Action was not executed"), str(e)))
  4937. return
  4938. def on_flipx(self):
  4939. """
  4940. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4941. :return:
  4942. """
  4943. self.defaults.report_usage("on_flipx()")
  4944. obj_list = self.collection.get_selected()
  4945. xminlist = []
  4946. yminlist = []
  4947. xmaxlist = []
  4948. ymaxlist = []
  4949. if not obj_list:
  4950. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4951. else:
  4952. try:
  4953. # first get a bounding box to fit all
  4954. for obj in obj_list:
  4955. xmin, ymin, xmax, ymax = obj.bounds()
  4956. xminlist.append(xmin)
  4957. yminlist.append(ymin)
  4958. xmaxlist.append(xmax)
  4959. ymaxlist.append(ymax)
  4960. # get the minimum x,y and maximum x,y for all objects selected
  4961. xminimal = min(xminlist)
  4962. yminimal = min(yminlist)
  4963. xmaximal = max(xmaxlist)
  4964. ymaximal = max(ymaxlist)
  4965. px = 0.5 * (xminimal + xmaximal)
  4966. py = 0.5 * (yminimal + ymaximal)
  4967. # execute mirroring
  4968. for obj in obj_list:
  4969. obj.mirror('Y', [px, py])
  4970. obj.plot()
  4971. self.app_obj.object_changed.emit(obj)
  4972. self.inform.emit('[success] %s.' % _("Flip on X axis done"))
  4973. except Exception as e:
  4974. self.app.inform.emit('[ERROR_NOTCL] %s: %s.' % (_("Action was not executed"), str(e)))
  4975. return
  4976. def on_rotate(self, silent=False, preset=None):
  4977. """
  4978. Executed when Options -> Rotate Selection menu entry is clicked.
  4979. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4980. :param preset: A value to be used as predefined angle for rotation.
  4981. :return:
  4982. """
  4983. self.defaults.report_usage("on_rotate()")
  4984. obj_list = self.collection.get_selected()
  4985. xminlist = []
  4986. yminlist = []
  4987. xmaxlist = []
  4988. ymaxlist = []
  4989. if not obj_list:
  4990. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4991. else:
  4992. if silent is False:
  4993. rotatebox = FCInputDoubleSpinner(title=_("Transform"), text=_("Enter the Angle value:"),
  4994. min=-360, max=360, decimals=4,
  4995. init_val=float(self.defaults['tools_transform_rotate']),
  4996. parent=self.ui)
  4997. rotatebox.setWindowIcon(QtGui.QIcon(self.resource_location + '/rotate.png'))
  4998. num, ok = rotatebox.get_value()
  4999. else:
  5000. num = preset
  5001. ok = True
  5002. if ok:
  5003. try:
  5004. # first get a bounding box to fit all
  5005. for obj in obj_list:
  5006. xmin, ymin, xmax, ymax = obj.bounds()
  5007. xminlist.append(xmin)
  5008. yminlist.append(ymin)
  5009. xmaxlist.append(xmax)
  5010. ymaxlist.append(ymax)
  5011. # get the minimum x,y and maximum x,y for all objects selected
  5012. xminimal = min(xminlist)
  5013. yminimal = min(yminlist)
  5014. xmaximal = max(xmaxlist)
  5015. ymaximal = max(ymaxlist)
  5016. px = 0.5 * (xminimal + xmaximal)
  5017. py = 0.5 * (yminimal + ymaximal)
  5018. for sel_obj in obj_list:
  5019. sel_obj.rotate(-float(num), point=(px, py))
  5020. sel_obj.plot()
  5021. self.app_obj.object_changed.emit(sel_obj)
  5022. self.inform.emit('[success] %s' % _("Rotation done."))
  5023. except Exception as e:
  5024. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5025. return
  5026. def on_skewx(self):
  5027. """
  5028. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5029. :return:
  5030. """
  5031. self.defaults.report_usage("on_skewx()")
  5032. obj_list = self.collection.get_selected()
  5033. xminlist = []
  5034. yminlist = []
  5035. if not obj_list:
  5036. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  5037. else:
  5038. skewxbox = FCInputDoubleSpinner(title=_("Transform"), text=_("Enter the Angle value:"),
  5039. min=-360, max=360, decimals=4,
  5040. init_val=float(self.defaults['tools_transform_skew_x']),
  5041. parent=self.ui)
  5042. skewxbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/skewX.png'))
  5043. num, ok = skewxbox.get_value()
  5044. if ok:
  5045. # first get a bounding box to fit all
  5046. for obj in obj_list:
  5047. xmin, ymin, xmax, ymax = obj.bounds()
  5048. xminlist.append(xmin)
  5049. yminlist.append(ymin)
  5050. # get the minimum x,y and maximum x,y for all objects selected
  5051. xminimal = min(xminlist)
  5052. yminimal = min(yminlist)
  5053. for obj in obj_list:
  5054. obj.skew(num, 0, point=(xminimal, yminimal))
  5055. obj.plot()
  5056. self.app_obj.object_changed.emit(obj)
  5057. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  5058. def on_skewy(self):
  5059. """
  5060. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5061. :return:
  5062. """
  5063. self.defaults.report_usage("on_skewy()")
  5064. obj_list = self.collection.get_selected()
  5065. xminlist = []
  5066. yminlist = []
  5067. if not obj_list:
  5068. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  5069. else:
  5070. skewybox = FCInputDoubleSpinner(title=_("Transform"), text=_("Enter the Angle value:"),
  5071. min=-360, max=360, decimals=4,
  5072. init_val=float(self.defaults['tools_transform_skew_y']),
  5073. parent=self.ui)
  5074. skewybox.setWindowIcon(QtGui.QIcon(self.resource_location + '/skewY.png'))
  5075. num, ok = skewybox.get_value()
  5076. if ok:
  5077. # first get a bounding box to fit all
  5078. for obj in obj_list:
  5079. xmin, ymin, xmax, ymax = obj.bounds()
  5080. xminlist.append(xmin)
  5081. yminlist.append(ymin)
  5082. # get the minimum x,y and maximum x,y for all objects selected
  5083. xminimal = min(xminlist)
  5084. yminimal = min(yminlist)
  5085. for obj in obj_list:
  5086. obj.skew(0, num, point=(xminimal, yminimal))
  5087. obj.plot()
  5088. self.app_obj.object_changed.emit(obj)
  5089. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  5090. def on_plots_updated(self):
  5091. """
  5092. Callback used to report when the plots have changed.
  5093. Adjust axes and zooms to fit.
  5094. :return: None
  5095. """
  5096. if self.is_legacy is False:
  5097. self.plotcanvas.update()
  5098. else:
  5099. self.plotcanvas.auto_adjust_axes()
  5100. self.on_zoom_fit()
  5101. self.collection.update_view()
  5102. # self.inform.emit(_("Plots updated ..."))
  5103. def on_toolbar_replot(self):
  5104. """
  5105. Callback for toolbar button. Re-plots all objects.
  5106. :return: None
  5107. """
  5108. self.log.debug("on_toolbar_replot()")
  5109. try:
  5110. obj = self.collection.get_active()
  5111. if obj:
  5112. obj.read_form()
  5113. else:
  5114. self.on_zoom_fit()
  5115. except AttributeError as e:
  5116. self.log.debug("on_toolbar_replot() -> %s" % str(e))
  5117. pass
  5118. self.plot_all()
  5119. def grid_status(self):
  5120. return True if self.ui.grid_snap_btn.isChecked() else False
  5121. def populate_cmenu_grids(self):
  5122. units = self.defaults['units'].lower()
  5123. # for act in self.ui.cmenu_gridmenu.actions():
  5124. # act.triggered.disconnect()
  5125. self.ui.cmenu_gridmenu.clear()
  5126. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5127. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5128. _("Grid On/Off"))
  5129. grid_toggle.setCheckable(True)
  5130. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5131. self.ui.cmenu_gridmenu.addSeparator()
  5132. for grid in sorted_list:
  5133. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5134. "%s" % str(grid))
  5135. action.triggered.connect(self.set_grid)
  5136. self.ui.cmenu_gridmenu.addSeparator()
  5137. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5138. _("Add"))
  5139. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5140. _("Delete"))
  5141. grid_add.triggered.connect(self.on_grid_add)
  5142. grid_delete.triggered.connect(self.on_grid_delete)
  5143. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5144. def set_grid(self):
  5145. menu_action = self.sender()
  5146. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5147. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5148. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5149. def on_grid_add(self):
  5150. # ## Current application units in lower Case
  5151. units = self.defaults['units'].lower()
  5152. grid_add_popup = FCInputDoubleSpinner(title=_("New Grid ..."),
  5153. text=_('Enter a Grid Value:'),
  5154. min=0.0000, max=99.9999, decimals=self.decimals,
  5155. parent=self.ui)
  5156. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5157. val, ok = grid_add_popup.get_value()
  5158. if ok:
  5159. if float(val) == 0:
  5160. self.inform.emit('[WARNING_NOTCL] %s' %
  5161. _("Please enter a grid value with non-zero value, in Float format."))
  5162. return
  5163. else:
  5164. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5165. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5166. self.inform.emit('[success] %s...' % _("New Grid added"))
  5167. else:
  5168. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5169. else:
  5170. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5171. def on_grid_delete(self):
  5172. # ## Current application units in lower Case
  5173. units = self.defaults['units'].lower()
  5174. grid_del_popup = FCInputDoubleSpinner(title="Delete Grid ...",
  5175. text='Enter a Grid Value:',
  5176. min=0.0000, max=99.9999, decimals=self.decimals,
  5177. parent=self.ui)
  5178. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5179. val, ok = grid_del_popup.get_value()
  5180. if ok:
  5181. if float(val) == 0:
  5182. self.inform.emit('[WARNING_NOTCL] %s' %
  5183. _("Please enter a grid value with non-zero value, in Float format."))
  5184. return
  5185. else:
  5186. try:
  5187. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5188. except ValueError:
  5189. self.inform.emit('[ERROR_NOTCL]%s...' % _("Grid Value does not exist"))
  5190. return
  5191. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5192. else:
  5193. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5194. def on_shortcut_list(self):
  5195. self.defaults.report_usage("on_shortcut_list()")
  5196. # add the tab if it was closed
  5197. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5198. # delete the absolute and relative position and messages in the infobar
  5199. # self.ui.position_label.setText("")
  5200. # self.ui.rel_position_label.setText("")
  5201. # hide coordinates toolbars in the infobar while in DB
  5202. self.ui.coords_toolbar.hide()
  5203. self.ui.delta_coords_toolbar.hide()
  5204. # Switch plot_area to preferences page
  5205. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5206. # self.ui.show()
  5207. def on_select_tab(self, name):
  5208. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5209. if self.ui.splitter.sizes()[0] == 0:
  5210. self.ui.splitter.setSizes([1, 1])
  5211. else:
  5212. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5213. self.ui.splitter.setSizes([0, 1])
  5214. if name == 'project':
  5215. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5216. elif name == 'properties':
  5217. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5218. elif name == 'tool':
  5219. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5220. def on_copy_name(self):
  5221. self.defaults.report_usage("on_copy_name()")
  5222. obj = self.collection.get_active()
  5223. try:
  5224. name = obj.options["name"]
  5225. except AttributeError:
  5226. self.log.debug("on_copy_name() --> No object selected to copy it's name")
  5227. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  5228. return
  5229. self.clipboard.setText(name)
  5230. self.inform.emit(_("Name copied to clipboard ..."))
  5231. def on_mouse_click_over_plot(self, event):
  5232. """
  5233. Default actions are:
  5234. :param event: Contains information about the event, like which button
  5235. was clicked, the pixel coordinates and the axes coordinates.
  5236. :return: None
  5237. """
  5238. self.pos = []
  5239. if self.is_legacy is False:
  5240. event_pos = event.pos
  5241. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5242. # # Set the mouse button for panning
  5243. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5244. else:
  5245. event_pos = (event.xdata, event.ydata)
  5246. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5247. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5248. # So it can receive key presses
  5249. self.plotcanvas.native.setFocus()
  5250. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5251. if self.grid_status():
  5252. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5253. else:
  5254. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5255. try:
  5256. if event.button == 1:
  5257. # Reset here the relative coordinates so there is a new reference on the click position
  5258. if self.rel_point1 is None:
  5259. self.rel_point1 = self.pos
  5260. else:
  5261. self.rel_point2 = copy(self.rel_point1)
  5262. self.rel_point1 = self.pos
  5263. self.on_mouse_move_over_plot(event, origin_click=True)
  5264. except Exception as e:
  5265. self.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5266. def on_mouse_double_click_over_plot(self, event):
  5267. if event.button == 1:
  5268. self.doubleclick = True
  5269. def on_mouse_move_over_plot(self, event, origin_click=None):
  5270. """
  5271. Callback for the mouse motion event over the plot.
  5272. :param event: Contains information about the event.
  5273. :param origin_click
  5274. :return: None
  5275. """
  5276. if self.is_legacy is False:
  5277. event_pos = event.pos
  5278. if self.defaults["global_pan_button"] == '2':
  5279. pan_button = 2
  5280. else:
  5281. pan_button = 3
  5282. self.event_is_dragging = event.is_dragging
  5283. else:
  5284. event_pos = (event.xdata, event.ydata)
  5285. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5286. if self.defaults["global_pan_button"] == '2':
  5287. pan_button = 3
  5288. else:
  5289. pan_button = 2
  5290. self.event_is_dragging = self.plotcanvas.is_dragging
  5291. # So it can receive key presses but not when the Tcl Shell is active
  5292. if not self.ui.shell_dock.isVisible():
  5293. if not self.plotcanvas.native.hasFocus():
  5294. self.plotcanvas.native.setFocus()
  5295. self.pos_jump = event_pos
  5296. self.ui.popMenu.mouse_is_panning = False
  5297. if origin_click is None:
  5298. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5299. if event.button == pan_button and self.event_is_dragging == 1:
  5300. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5301. if self.ui.popMenu.popup_active:
  5302. self.ui.popMenu.popup_active = False
  5303. return
  5304. self.ui.popMenu.mouse_is_panning = True
  5305. return
  5306. if self.rel_point1 is not None:
  5307. try: # May fail in case mouse not within axes
  5308. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5309. if pos_canvas[0] is None or pos_canvas[1] is None:
  5310. return
  5311. if self.grid_status():
  5312. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5313. # Update cursor
  5314. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5315. symbol='++', edge_color=self.cursor_color_3D,
  5316. edge_width=self.defaults["global_cursor_width"],
  5317. size=self.defaults["global_cursor_size"])
  5318. else:
  5319. pos = (pos_canvas[0], pos_canvas[1])
  5320. self.dx = pos[0] - float(self.rel_point1[0])
  5321. self.dy = pos[1] - float(self.rel_point1[1])
  5322. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5323. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5324. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5325. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5326. units = self.defaults["units"].lower()
  5327. self.plotcanvas.text_hud.text = \
  5328. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5329. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5330. self.mouse = [pos[0], pos[1]]
  5331. if self.defaults['global_selection_shape'] is False:
  5332. self.selection_type = None
  5333. return
  5334. # if the mouse is moved and the LMB is clicked then the action is a selection
  5335. if self.event_is_dragging == 1 and event.button == 1:
  5336. self.delete_selection_shape()
  5337. if self.dx < 0:
  5338. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5339. face_color=self.defaults['global_alt_sel_fill'])
  5340. self.selection_type = False
  5341. elif self.dx >= 0:
  5342. self.draw_moving_selection_shape(self.pos, pos)
  5343. self.selection_type = True
  5344. else:
  5345. self.selection_type = None
  5346. else:
  5347. self.selection_type = None
  5348. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5349. if self.defaults['global_hover']:
  5350. for obj in self.collection.get_list():
  5351. try:
  5352. # select the object(s) only if it is enabled (plotted)
  5353. if obj.options['plot']:
  5354. if obj not in self.collection.get_selected():
  5355. poly_obj = Polygon(
  5356. [(obj.options['xmin'], obj.options['ymin']),
  5357. (obj.options['xmax'], obj.options['ymin']),
  5358. (obj.options['xmax'], obj.options['ymax']),
  5359. (obj.options['xmin'], obj.options['ymax'])]
  5360. )
  5361. if Point(pos).within(poly_obj):
  5362. if obj.isHovering is False:
  5363. obj.isHovering = True
  5364. obj.notHovering = True
  5365. # create the selection box around the selected object
  5366. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5367. else:
  5368. if obj.notHovering is True:
  5369. obj.notHovering = False
  5370. obj.isHovering = False
  5371. self.delete_hover_shape()
  5372. except Exception:
  5373. # the Exception here will happen if we try to select on screen and we have an
  5374. # newly (and empty) just created Geometry or Excellon object that do not have the
  5375. # xmin, xmax, ymin, ymax options.
  5376. # In this case poly_obj creation (see above) will fail
  5377. pass
  5378. except Exception as e:
  5379. self.log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5380. self.ui.position_label.setText("")
  5381. self.ui.rel_position_label.setText("")
  5382. self.mouse = None
  5383. def on_mouse_click_release_over_plot(self, event):
  5384. """
  5385. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5386. and has been registered in ''self.__init__()''.
  5387. :param event: contains information about the event.
  5388. :return:
  5389. """
  5390. if self.is_legacy is False:
  5391. event_pos = event.pos
  5392. right_button = 2
  5393. else:
  5394. event_pos = (event.xdata, event.ydata)
  5395. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5396. right_button = 3
  5397. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5398. if self.grid_status():
  5399. try:
  5400. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5401. except TypeError:
  5402. return
  5403. else:
  5404. pos = (pos_canvas[0], pos_canvas[1])
  5405. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5406. # canvas menu
  5407. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5408. self.ui.popMenu.mouse_is_panning = False
  5409. self.cursor = QtGui.QCursor()
  5410. self.populate_cmenu_grids()
  5411. self.ui.popMenu.popup(self.cursor.pos())
  5412. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5413. # selection and then select a type of selection ("enclosing" or "touching")
  5414. if event.button == 1: # left click
  5415. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5416. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5417. if modifiers == QtCore.Qt.ShiftModifier:
  5418. # do not auto open the Project Tab
  5419. self.click_noproject = True
  5420. self.clipboard.setText(
  5421. self.defaults["global_point_clipboard_format"] %
  5422. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5423. )
  5424. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5425. return
  5426. # the object selection on canvas does not work for App Tools or for Editors
  5427. if self.call_source != 'app':
  5428. return
  5429. if self.doubleclick is True:
  5430. self.doubleclick = False
  5431. if self.collection.get_selected():
  5432. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5433. if self.ui.splitter.sizes()[0] == 0:
  5434. self.ui.splitter.setSizes([1, 1])
  5435. try:
  5436. # delete the selection shape(S) as it may be in the way
  5437. self.delete_selection_shape()
  5438. self.delete_hover_shape()
  5439. except Exception as e:
  5440. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5441. return
  5442. else:
  5443. # WORKAROUND for LEGACY MODE
  5444. if self.is_legacy is True:
  5445. # if there is no move on canvas then we have no dragging selection
  5446. if self.dx == 0 or self.dy == 0:
  5447. self.selection_type = None
  5448. if self.selection_type is not None:
  5449. try:
  5450. self.selection_area_handler(self.pos, pos, self.selection_type)
  5451. self.selection_type = None
  5452. except Exception as e:
  5453. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5454. return
  5455. else:
  5456. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5457. if key_modifier == QtCore.Qt.ShiftModifier:
  5458. mod_key = 'Shift'
  5459. elif key_modifier == QtCore.Qt.ControlModifier:
  5460. mod_key = 'Control'
  5461. else:
  5462. mod_key = None
  5463. try:
  5464. if self.command_active is None:
  5465. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5466. # deselect, and if it's not selected then it will be selected
  5467. # If there is no active command (self.command_active is None) then we check if we clicked
  5468. # on a object by checking the bounding limits against mouse click position
  5469. if mod_key == self.defaults["global_mselect_key"]:
  5470. self.select_objects(key='multisel')
  5471. else:
  5472. # If there is no active command (self.command_active is None) then we check if
  5473. # we clicked on a object by checking the bounding limits against mouse click position
  5474. self.select_objects()
  5475. self.delete_hover_shape()
  5476. except Exception as e:
  5477. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5478. return
  5479. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5480. """
  5481. :param start_pos: mouse position when the selection LMB click was done
  5482. :param end_pos: mouse position when the left mouse button is released
  5483. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5484. :return:
  5485. """
  5486. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5487. # delete previous selection shape
  5488. self.delete_selection_shape()
  5489. # make all objects inactive
  5490. self.collection.set_all_inactive()
  5491. for obj in self.collection.get_list():
  5492. try:
  5493. # select the object(s) only if it is enabled (plotted)
  5494. if obj.options['plot']:
  5495. # it's a line without area
  5496. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5497. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5498. # it's a geometry with area
  5499. else:
  5500. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5501. (obj.options['xmax'], obj.options['ymin']),
  5502. (obj.options['xmax'], obj.options['ymax']),
  5503. (obj.options['xmin'], obj.options['ymax'])])
  5504. if poly_obj.is_empty or not poly_obj.is_valid:
  5505. continue
  5506. if sel_type is True:
  5507. if poly_obj.within(poly_selection):
  5508. # create the selection box around the selected object
  5509. if self.defaults['global_selection_shape'] is True:
  5510. self.draw_selection_shape(obj)
  5511. self.collection.set_active(obj.options['name'])
  5512. else:
  5513. if poly_selection.intersects(poly_obj):
  5514. # create the selection box around the selected object
  5515. if self.defaults['global_selection_shape'] is True:
  5516. self.draw_selection_shape(obj)
  5517. self.collection.set_active(obj.options['name'])
  5518. obj.selection_shape_drawn = True
  5519. except Exception as e:
  5520. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5521. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5522. # In this case poly_obj creation (see above) will fail
  5523. self.log.debug("App.selection_area_handler() --> %s" % str(e))
  5524. def select_objects(self, key=None):
  5525. """
  5526. Will select objects clicked on canvas
  5527. :param key: for future use in cumulative selection
  5528. :return:
  5529. """
  5530. # list where we store the overlapped objects under our mouse left click position
  5531. if key is None:
  5532. self.objects_under_the_click_list = []
  5533. # Populate the list with the overlapped objects on the click position
  5534. curr_x, curr_y = self.pos
  5535. for obj in self.all_objects_list:
  5536. # ScriptObject and DocumentObject objects can't be selected
  5537. if obj.kind == 'script' or obj.kind == 'document':
  5538. continue
  5539. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5540. continue
  5541. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5542. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5543. if obj.options['name'] not in self.objects_under_the_click_list:
  5544. if obj.options['plot']:
  5545. # add objects to the objects_under_the_click list only if the object is plotted
  5546. # (active and not disabled)
  5547. self.objects_under_the_click_list.append(obj.options['name'])
  5548. try:
  5549. if self.objects_under_the_click_list:
  5550. curr_sel_obj = self.collection.get_active()
  5551. # case when there is only an object under the click and we toggle it
  5552. if len(self.objects_under_the_click_list) == 1:
  5553. if curr_sel_obj is None:
  5554. self.collection.set_active(self.objects_under_the_click_list[0])
  5555. curr_sel_obj = self.collection.get_active()
  5556. # create the selection box around the selected object
  5557. if self.defaults['global_selection_shape'] is True:
  5558. self.draw_selection_shape(curr_sel_obj)
  5559. curr_sel_obj.selection_shape_drawn = True
  5560. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5561. self.collection.on_objects_selection(False)
  5562. self.delete_selection_shape()
  5563. curr_sel_obj.selection_shape_drawn = False
  5564. self.collection.set_active(self.objects_under_the_click_list[0])
  5565. curr_sel_obj = self.collection.get_active()
  5566. # create the selection box around the selected object
  5567. if self.defaults['global_selection_shape'] is True:
  5568. self.draw_selection_shape(curr_sel_obj)
  5569. curr_sel_obj.selection_shape_drawn = True
  5570. self.selected_message(curr_sel_obj=curr_sel_obj)
  5571. elif curr_sel_obj.selection_shape_drawn is False:
  5572. if self.defaults['global_selection_shape'] is True:
  5573. self.draw_selection_shape(curr_sel_obj)
  5574. curr_sel_obj.selection_shape_drawn = True
  5575. else:
  5576. self.collection.on_objects_selection(False)
  5577. self.delete_selection_shape()
  5578. if self.call_source != 'app':
  5579. self.call_source = 'app'
  5580. self.selected_message(curr_sel_obj=curr_sel_obj)
  5581. else:
  5582. # If there is no selected object
  5583. # make active the first element of the overlapped objects list
  5584. if self.collection.get_active() is None:
  5585. self.collection.set_active(self.objects_under_the_click_list[0])
  5586. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5587. name_sel_obj = self.collection.get_active().options['name']
  5588. # In case that there is a selected object but it is not in the overlapped object list
  5589. # make that object inactive and activate the first element in the overlapped object list
  5590. if name_sel_obj not in self.objects_under_the_click_list:
  5591. self.collection.set_inactive(name_sel_obj)
  5592. name_sel_obj = self.objects_under_the_click_list[0]
  5593. self.collection.set_active(name_sel_obj)
  5594. else:
  5595. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5596. self.collection.set_all_inactive()
  5597. self.collection.set_active(
  5598. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5599. curr_sel_obj = self.collection.get_active()
  5600. # delete the possible selection box around a possible selected object
  5601. self.delete_selection_shape()
  5602. curr_sel_obj.selection_shape_drawn = False
  5603. # create the selection box around the selected object
  5604. if self.defaults['global_selection_shape'] is True:
  5605. self.draw_selection_shape(curr_sel_obj)
  5606. curr_sel_obj.selection_shape_drawn = True
  5607. self.selected_message(curr_sel_obj=curr_sel_obj)
  5608. else:
  5609. # deselect everything
  5610. self.collection.on_objects_selection(False)
  5611. # delete the possible selection box around a possible selected object
  5612. self.delete_selection_shape()
  5613. for o in self.collection.get_list():
  5614. o.selection_shape_drawn = False
  5615. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5616. # only when working on App
  5617. if self.call_source == 'app':
  5618. if self.click_noproject is False:
  5619. # if the Tool Tab is in focus don't change focus to Project Tab
  5620. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5621. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5622. else:
  5623. # restore auto open the Project Tab
  5624. self.click_noproject = False
  5625. # delete any text in the status bar, implicitly the last object name that was selected
  5626. # self.inform.emit("")
  5627. else:
  5628. self.call_source = 'app'
  5629. except Exception as e:
  5630. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5631. def selected_message(self, curr_sel_obj):
  5632. if curr_sel_obj:
  5633. if curr_sel_obj.kind == 'gerber':
  5634. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5635. color='green',
  5636. name=str(curr_sel_obj.options['name']),
  5637. tx=_("selected"))
  5638. )
  5639. elif curr_sel_obj.kind == 'excellon':
  5640. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5641. color='brown',
  5642. name=str(curr_sel_obj.options['name']),
  5643. tx=_("selected"))
  5644. )
  5645. elif curr_sel_obj.kind == 'cncjob':
  5646. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5647. color='blue',
  5648. name=str(curr_sel_obj.options['name']),
  5649. tx=_("selected"))
  5650. )
  5651. elif curr_sel_obj.kind == 'geometry':
  5652. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5653. color='red',
  5654. name=str(curr_sel_obj.options['name']),
  5655. tx=_("selected"))
  5656. )
  5657. def delete_hover_shape(self):
  5658. self.hover_shapes.clear()
  5659. self.hover_shapes.redraw()
  5660. def draw_hover_shape(self, sel_obj, color=None):
  5661. """
  5662. :param sel_obj: The object for which the hover shape must be drawn
  5663. :param color: The color of the hover shape
  5664. :return: None
  5665. """
  5666. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5667. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5668. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5669. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5670. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5671. if self.defaults['units'].upper() == 'MM':
  5672. hover_rect = hover_rect.buffer(-0.1)
  5673. hover_rect = hover_rect.buffer(0.2)
  5674. else:
  5675. hover_rect = hover_rect.buffer(-0.00393)
  5676. hover_rect = hover_rect.buffer(0.00787)
  5677. # if color:
  5678. # face = Color(color)
  5679. # face.alpha = 0.2
  5680. # outline = Color(color, alpha=0.8)
  5681. # else:
  5682. # face = Color(self.defaults['global_sel_fill'])
  5683. # face.alpha = 0.2
  5684. # outline = self.defaults['global_sel_line']
  5685. if color:
  5686. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5687. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5688. else:
  5689. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5690. outline = self.defaults['global_sel_line']
  5691. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5692. if self.is_legacy is True:
  5693. self.hover_shapes.redraw()
  5694. def delete_selection_shape(self):
  5695. self.move_tool.sel_shapes.clear()
  5696. self.move_tool.sel_shapes.redraw()
  5697. def draw_selection_shape(self, sel_obj, color=None):
  5698. """
  5699. Will draw a selection shape around the selected object.
  5700. :param sel_obj: The object for which the selection shape must be drawn
  5701. :param color: The color for the selection shape.
  5702. :return: None
  5703. """
  5704. if sel_obj is None:
  5705. return
  5706. # it's a line without area
  5707. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5708. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5709. # it's a geometry with area
  5710. else:
  5711. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5712. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5713. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5714. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5715. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5716. b_sel_rect = None
  5717. try:
  5718. if self.defaults['units'].upper() == 'MM':
  5719. b_sel_rect = sel_rect.buffer(-0.1)
  5720. b_sel_rect = b_sel_rect.buffer(0.2)
  5721. else:
  5722. b_sel_rect = sel_rect.buffer(-0.00393)
  5723. b_sel_rect = b_sel_rect.buffer(0.00787)
  5724. except Exception:
  5725. pass
  5726. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5727. b_sel_rect = sel_rect
  5728. if color:
  5729. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5730. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5731. else:
  5732. if self.is_legacy is False:
  5733. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5734. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5735. else:
  5736. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5737. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5738. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5739. color=outline,
  5740. face_color=face,
  5741. update=True,
  5742. layer=0,
  5743. tolerance=None))
  5744. if self.is_legacy is True:
  5745. self.move_tool.sel_shapes.redraw()
  5746. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5747. """
  5748. Will draw a selection shape when dragging mouse on canvas.
  5749. :param old_coords: Old coordinates
  5750. :param coords: New coordinates
  5751. :param kwargs: Keyword arguments
  5752. :return:
  5753. """
  5754. if 'color' in kwargs:
  5755. color = kwargs['color']
  5756. else:
  5757. color = self.defaults['global_sel_line']
  5758. if 'face_color' in kwargs:
  5759. face_color = kwargs['face_color']
  5760. else:
  5761. face_color = self.defaults['global_sel_fill']
  5762. if 'face_alpha' in kwargs:
  5763. face_alpha = kwargs['face_alpha']
  5764. else:
  5765. face_alpha = 0.3
  5766. x0, y0 = old_coords
  5767. x1, y1 = coords
  5768. pt1 = (x0, y0)
  5769. pt2 = (x1, y0)
  5770. pt3 = (x1, y1)
  5771. pt4 = (x0, y1)
  5772. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5773. # color_t = Color(face_color)
  5774. # color_t.alpha = face_alpha
  5775. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5776. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5777. layer=0, tolerance=None)
  5778. if self.is_legacy is True:
  5779. self.move_tool.sel_shapes.redraw()
  5780. def obj_properties(self):
  5781. """
  5782. Will launch the object Properties Tool
  5783. :return:
  5784. """
  5785. self.defaults.report_usage("obj_properties()")
  5786. self.properties_tool.run(toggle=False)
  5787. def on_project_context_save(self):
  5788. """
  5789. Wrapper, will save the object function of it's type
  5790. :return:
  5791. """
  5792. sel_objects = self.collection.get_selected()
  5793. len_objects = len(sel_objects)
  5794. cnt = 0
  5795. if len_objects > 1:
  5796. for o in sel_objects:
  5797. if o.kind == 'cncjob':
  5798. cnt += 1
  5799. if len_objects == cnt:
  5800. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5801. _filter_ = self.defaults['cncjob_save_filters'] + \
  5802. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5803. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5804. try:
  5805. filename, _f = FCFileSaveDialog.get_saved_filename(
  5806. caption=_("Export Code ..."),
  5807. directory=dir_file_to_save,
  5808. ext_filter=_filter_
  5809. )
  5810. except TypeError:
  5811. filename, _f = FCFileSaveDialog.get_saved_filename(
  5812. caption=_("Export Code ..."),
  5813. ext_filter=_filter_)
  5814. filename = filename.rpartition('/')[0]
  5815. for ob in sel_objects:
  5816. ob.read_form()
  5817. fname = '%s/%s' % (filename, ob.options['name'])
  5818. ob.export_gcode_handler(fname, is_gcode=True)
  5819. return
  5820. obj = self.collection.get_active()
  5821. if type(obj) == GeometryObject:
  5822. self.f_handlers.on_file_exportdxf()
  5823. elif type(obj) == ExcellonObject:
  5824. self.f_handlers.on_file_saveexcellon()
  5825. elif type(obj) == CNCJobObject:
  5826. obj.on_exportgcode_button_click()
  5827. elif type(obj) == GerberObject:
  5828. self.f_handlers.on_file_savegerber()
  5829. elif type(obj) == ScriptObject:
  5830. self.f_handlers.on_file_savescript()
  5831. elif type(obj) == DocumentObject:
  5832. self.f_handlers.on_file_savedocument()
  5833. def obj_move(self):
  5834. """
  5835. Callback for the Move menu entry in various Context Menu's.
  5836. :return:
  5837. """
  5838. self.defaults.report_usage("obj_move()")
  5839. self.move_tool.run(toggle=False)
  5840. # ###############################################################################################################
  5841. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5842. # ###############################################################################################################
  5843. def init_code_editor(self, name):
  5844. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5845. # add the tab if it was closed
  5846. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5847. self.text_editor_tab.setObjectName('text_editor_tab')
  5848. # delete the absolute and relative position and messages in the infobar
  5849. # self.ui.position_label.setText("")
  5850. # self.ui.rel_position_label.setText("")
  5851. # hide coordinates toolbars in the infobar while in DB
  5852. self.ui.coords_toolbar.hide()
  5853. self.ui.delta_coords_toolbar.hide()
  5854. self.toggle_codeeditor = True
  5855. self.text_editor_tab.code_editor.completer_enable = False
  5856. self.text_editor_tab.buttonRun.hide()
  5857. # make sure to keep a reference to the code editor
  5858. self.reference_code_editor = self.text_editor_tab.code_editor
  5859. # Switch plot_area to CNCJob tab
  5860. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5861. def on_view_source(self):
  5862. """
  5863. Called when the user wants to see the source file of the selected object
  5864. :return:
  5865. """
  5866. try:
  5867. obj = self.collection.get_active()
  5868. except Exception as e:
  5869. self.log.debug("App.on_view_source() --> %s" % str(e))
  5870. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5871. return 'fail'
  5872. if obj is None:
  5873. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5874. return 'fail'
  5875. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5876. self.proc_container.view.set_busy('%s...' % _("Loading"))
  5877. flt = "All Files (*.*)"
  5878. if obj.kind == 'gerber':
  5879. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5880. elif obj.kind == 'excellon':
  5881. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5882. elif obj.kind == 'cncjob':
  5883. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5884. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5885. # add the tab if it was closed
  5886. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5887. self.source_editor_tab.setObjectName('source_editor_tab')
  5888. # delete the absolute and relative position and messages in the infobar
  5889. # self.ui.position_label.setText("")
  5890. # self.ui.rel_position_label.setText("")
  5891. # hide coordinates toolbars in the infobar while in DB
  5892. self.ui.coords_toolbar.hide()
  5893. self.ui.delta_coords_toolbar.hide()
  5894. self.source_editor_tab.code_editor.completer_enable = False
  5895. self.source_editor_tab.buttonRun.hide()
  5896. # Switch plot_area to CNCJob tab
  5897. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5898. try:
  5899. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5900. except TypeError:
  5901. pass
  5902. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5903. try:
  5904. self.source_editor_tab.buttonSave.clicked.disconnect()
  5905. except TypeError:
  5906. pass
  5907. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5908. # then append the text from GCode to the text editor
  5909. if obj.kind == 'cncjob':
  5910. try:
  5911. file = obj.export_gcode(to_file=True)
  5912. if file == 'fail':
  5913. return 'fail'
  5914. except AttributeError:
  5915. self.inform.emit('[WARNING_NOTCL] %s' %
  5916. _("There is no selected object for which to see it's source file code."))
  5917. return 'fail'
  5918. else:
  5919. try:
  5920. file = StringIO(obj.source_file)
  5921. except (AttributeError, TypeError):
  5922. self.inform.emit('[WARNING_NOTCL] %s' %
  5923. _("There is no selected object for which to see it's source file code."))
  5924. return 'fail'
  5925. self.source_editor_tab.t_frame.hide()
  5926. try:
  5927. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5928. except Exception as e:
  5929. self.log.debug('App.on_view_source() -->%s' % str(e))
  5930. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5931. return
  5932. self.source_editor_tab.t_frame.show()
  5933. self.proc_container.view.set_idle()
  5934. # self.ui.show()
  5935. def on_toggle_code_editor(self):
  5936. self.defaults.report_usage("on_toggle_code_editor()")
  5937. if self.toggle_codeeditor is False:
  5938. self.init_code_editor(name=_("Code Editor"))
  5939. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5940. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5941. self.text_editor_tab.buttonSave.clicked.disconnect()
  5942. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5943. else:
  5944. for idx in range(self.ui.plot_tab_area.count()):
  5945. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5946. self.ui.plot_tab_area.closeTab(idx)
  5947. break
  5948. self.toggle_codeeditor = False
  5949. def on_code_editor_close(self):
  5950. self.toggle_codeeditor = False
  5951. def goto_text_line(self):
  5952. """
  5953. Will scroll a text to the specified text line.
  5954. :return: None
  5955. """
  5956. dia_box = Dialog_box(title=_("Go to Line ..."),
  5957. label='%s:' % _("Line"),
  5958. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5959. initial_text='')
  5960. try:
  5961. line = int(dia_box.location) - 1
  5962. except (ValueError, TypeError):
  5963. line = 0
  5964. if dia_box.ok:
  5965. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5966. # at the top of the window
  5967. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5968. # get the document() of the AppTextEditor
  5969. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5970. # create a Text Cursor based on the searched line
  5971. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5972. # set cursor of the code editor with the cursor at the searcehd line
  5973. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5974. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5975. """
  5976. Re-generates all plots from all objects.
  5977. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5978. :param muted: if True don't print messages
  5979. :param use_thread: if True will use threading for plotting the objects
  5980. :return: None
  5981. """
  5982. self.log.debug("Plot_all()")
  5983. if muted is not True:
  5984. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5985. for plot_obj in self.collection.get_list():
  5986. def worker_task(obj):
  5987. with self.proc_container.new("Plotting"):
  5988. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5989. if fit_view is True:
  5990. self.app_obj.object_plotted.emit(obj)
  5991. if use_thread is True:
  5992. # Send to worker
  5993. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5994. else:
  5995. worker_task(plot_obj)
  5996. def register_folder(self, filename):
  5997. """
  5998. Register the last folder used by the app to open something
  5999. :param filename: the last folder is extracted from the filename
  6000. :return: None
  6001. """
  6002. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6003. def register_save_folder(self, filename):
  6004. """
  6005. Register the last folder used by the app to save something
  6006. :param filename: the last folder is extracted from the filename
  6007. :return: None
  6008. """
  6009. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6010. # def set_progress_bar(self, percentage, text=""):
  6011. # """
  6012. # Set a progress bar to a value (percentage)
  6013. #
  6014. # :param percentage: Value set to the progressbar
  6015. # :param text: Not used
  6016. # :return: None
  6017. # """
  6018. # self.ui.progress_bar.setValue(int(percentage))
  6019. def setup_recent_items(self):
  6020. """
  6021. Setup a dictionary with the recent files accessed, organized by type
  6022. :return:
  6023. """
  6024. icons = {
  6025. "gerber": self.resource_location + "/flatcam_icon16.png",
  6026. "excellon": self.resource_location + "/drill16.png",
  6027. 'geometry': self.resource_location + "/geometry16.png",
  6028. "cncjob": self.resource_location + "/cnc16.png",
  6029. "script": self.resource_location + "/script_new24.png",
  6030. "document": self.resource_location + "/notes16_1.png",
  6031. "project": self.resource_location + "/project16.png",
  6032. "svg": self.resource_location + "/geometry16.png",
  6033. "dxf": self.resource_location + "/dxf16.png",
  6034. "pdf": self.resource_location + "/pdf32.png",
  6035. "image": self.resource_location + "/image16.png"
  6036. }
  6037. try:
  6038. image_opener = self.image_tool.import_image
  6039. except AttributeError:
  6040. image_opener = None
  6041. openers = {
  6042. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  6043. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  6044. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  6045. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  6046. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  6047. "document": None,
  6048. 'project': self.f_handlers.open_project,
  6049. 'svg': self.f_handlers.import_svg,
  6050. 'dxf': self.f_handlers.import_dxf,
  6051. 'image': image_opener,
  6052. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6053. }
  6054. # Open recent file for files
  6055. try:
  6056. f = open(self.data_path + '/recent.json')
  6057. except IOError:
  6058. App.log.error("Failed to load recent item list.")
  6059. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  6060. return
  6061. try:
  6062. self.recent = json.load(f)
  6063. except json.errors.JSONDecodeError:
  6064. App.log.error("Failed to parse recent item list.")
  6065. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  6066. f.close()
  6067. return
  6068. f.close()
  6069. # Open recent file for projects
  6070. try:
  6071. fp = open(self.data_path + '/recent_projects.json')
  6072. except IOError:
  6073. App.log.error("Failed to load recent project item list.")
  6074. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  6075. return
  6076. try:
  6077. self.recent_projects = json.load(fp)
  6078. except json.errors.JSONDecodeError:
  6079. App.log.error("Failed to parse recent project item list.")
  6080. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  6081. fp.close()
  6082. return
  6083. fp.close()
  6084. # Closure needed to create callbacks in a loop.
  6085. # Otherwise late binding occurs.
  6086. def make_callback(func, fname):
  6087. def opener():
  6088. func(fname)
  6089. return opener
  6090. def reset_recent_files():
  6091. # Reset menu
  6092. self.ui.recent.clear()
  6093. self.recent = []
  6094. try:
  6095. ff = open(self.data_path + '/recent.json', 'w')
  6096. except IOError:
  6097. App.log.error("Failed to open recent items file for writing.")
  6098. return
  6099. json.dump(self.recent, ff)
  6100. def reset_recent_projects():
  6101. # Reset menu
  6102. self.ui.recent_projects.clear()
  6103. self.recent_projects = []
  6104. try:
  6105. frp = open(self.data_path + '/recent_projects.json', 'w')
  6106. except IOError:
  6107. App.log.error("Failed to open recent projects items file for writing.")
  6108. return
  6109. json.dump(self.recent, frp)
  6110. # Reset menu
  6111. self.ui.recent.clear()
  6112. self.ui.recent_projects.clear()
  6113. # Create menu items for projects
  6114. for recent in self.recent_projects:
  6115. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6116. if recent['kind'] == 'project':
  6117. try:
  6118. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6119. # Attach callback
  6120. o = make_callback(openers[recent["kind"]], recent['filename'])
  6121. action.triggered.connect(o)
  6122. self.ui.recent_projects.addAction(action)
  6123. except KeyError:
  6124. App.log.error("Unsupported file type: %s" % recent["kind"])
  6125. # Last action in Recent Files menu is one that Clear the content
  6126. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  6127. (_("Clear Recent projects")), self)
  6128. clear_action_proj.triggered.connect(reset_recent_projects)
  6129. self.ui.recent_projects.addSeparator()
  6130. self.ui.recent_projects.addAction(clear_action_proj)
  6131. # Create menu items for files
  6132. for recent in self.recent:
  6133. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6134. if recent['kind'] != 'project':
  6135. try:
  6136. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6137. # Attach callback
  6138. o = make_callback(openers[recent["kind"]], recent['filename'])
  6139. action.triggered.connect(o)
  6140. self.ui.recent.addAction(action)
  6141. except KeyError:
  6142. App.log.error("Unsupported file type: %s" % recent["kind"])
  6143. # Last action in Recent Files menu is one that Clear the content
  6144. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  6145. (_("Clear Recent files")), self)
  6146. clear_action.triggered.connect(reset_recent_files)
  6147. self.ui.recent.addSeparator()
  6148. self.ui.recent.addAction(clear_action)
  6149. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6150. # self.ui.menufilerecent.set_submenu(recent_menu)
  6151. # recent_menu.show_all()
  6152. # self.ui.recent.show()
  6153. self.log.debug("Recent items list has been populated.")
  6154. def on_properties_tab_click(self, index):
  6155. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  6156. self.setup_default_properties_tab()
  6157. def setup_default_properties_tab(self):
  6158. """
  6159. Default text for the Properties tab when is not taken by the Object UI.
  6160. :return:
  6161. """
  6162. # label = QtWidgets.QLabel("Choose an item from Project")
  6163. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6164. # sel_title = QtWidgets.QTextEdit()
  6165. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6166. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6167. #
  6168. # f_settings = QSettings("Open Source", "FlatCAM")
  6169. # if f_settings.contains("notebook_font_size"):
  6170. # fsize = f_settings.value('notebook_font_size', type=int)
  6171. # else:
  6172. # fsize = 12
  6173. #
  6174. # tsize = fsize + int(fsize / 2)
  6175. #
  6176. # selected_text = ''
  6177. #
  6178. # sel_title.setText(selected_text)
  6179. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6180. # Tree Widget
  6181. d_properties_tw = FCTree(columns=2)
  6182. d_properties_tw.setObjectName("default_properties")
  6183. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6184. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  6185. root = d_properties_tw.invisibleRootItem()
  6186. font = QtGui.QFont()
  6187. font.setBold(True)
  6188. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6189. # main Items categories
  6190. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6191. d_properties_tw.addChild(parent=general_cat,
  6192. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6193. d_properties_tw.addChild(parent=general_cat,
  6194. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6195. d_properties_tw.addChild(parent=general_cat,
  6196. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6197. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6198. d_properties_tw.addChild(parent=grid_cat,
  6199. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6200. column1=True)
  6201. d_properties_tw.addChild(parent=grid_cat,
  6202. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6203. column1=True)
  6204. d_properties_tw.addChild(parent=grid_cat,
  6205. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6206. column1=True)
  6207. d_properties_tw.addChild(parent=grid_cat,
  6208. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6209. column1=True)
  6210. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6211. d_properties_tw.addChild(parent=canvas_cat,
  6212. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6213. column1=True)
  6214. d_properties_tw.addChild(parent=canvas_cat,
  6215. title=['%s:' % _("Workspace active"),
  6216. '%s' % str(self.defaults['global_workspace'])],
  6217. column1=True)
  6218. d_properties_tw.addChild(parent=canvas_cat,
  6219. title=['%s:' % _("Workspace size"),
  6220. '%s' % str(self.defaults['global_workspaceT'])],
  6221. column1=True)
  6222. d_properties_tw.addChild(parent=canvas_cat,
  6223. title=['%s:' % _("Workspace orientation"),
  6224. '%s' % _("Portrait") if self.defaults[
  6225. 'global_workspace_orientation'] == 'p' else
  6226. _("Landscape")],
  6227. column1=True)
  6228. d_properties_tw.addChild(parent=canvas_cat,
  6229. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6230. column1=True)
  6231. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6232. def setup_obj_classes(self):
  6233. """
  6234. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6235. class.
  6236. :return: None
  6237. """
  6238. FlatCAMObj.app = self
  6239. ObjectCollection.app = self
  6240. Gerber.app = self
  6241. Excellon.app = self
  6242. Geometry.app = self
  6243. CNCjob.app = self
  6244. FCProcess.app = self
  6245. FCProcessContainer.app = self
  6246. OptionsGroupUI.app = self
  6247. def version_check(self):
  6248. """
  6249. Checks for the latest version of the program. Alerts the
  6250. user if theirs is outdated. This method is meant to be run
  6251. in a separate thread.
  6252. :return: None
  6253. """
  6254. self.log.debug("version_check()")
  6255. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6256. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6257. App.version_url,
  6258. str(self.defaults['global_serial']),
  6259. str(self.version),
  6260. str(self.os),
  6261. urllib.parse.urlencode(self.defaults["global_stats"])
  6262. )
  6263. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6264. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6265. # urllib.parse.urlencode(self.defaults["global_stats"])
  6266. else:
  6267. # no_stats dict; just so it won't break things on website
  6268. no_ststs_dict = {"global_ststs": {}}
  6269. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6270. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6271. self.log.debug("Checking for updates @ %s" % full_url)
  6272. # ## Get the data
  6273. try:
  6274. f = urllib.request.urlopen(full_url)
  6275. except Exception:
  6276. # App.log.warning("Failed checking for latest version. Could not connect.")
  6277. self.log.warning("Failed checking for latest version. Could not connect.")
  6278. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6279. return
  6280. try:
  6281. data = json.load(f)
  6282. except Exception as e:
  6283. App.log.error("Could not parse information about latest version.")
  6284. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6285. self.log.debug("json.load(): %s" % str(e))
  6286. f.close()
  6287. return
  6288. f.close()
  6289. # ## Latest version?
  6290. if self.version >= data["version"]:
  6291. self.log.debug("FlatCAM is up to date!")
  6292. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6293. return
  6294. self.log.debug("Newer version available.")
  6295. self.message.emit(
  6296. _("Newer Version Available"),
  6297. '%s<br><br>><b>%s</b><br>%s' % (
  6298. _("There is a newer version of FlatCAM available for download:"),
  6299. str(data["name"]),
  6300. str(data["message"])
  6301. ),
  6302. _("info")
  6303. )
  6304. def on_plotcanvas_setup(self, container=None):
  6305. """
  6306. This is doing the setup for the plot area (canvas).
  6307. :param container: QT Widget where to install the canvas
  6308. :return: None
  6309. """
  6310. if container:
  6311. plot_container = container
  6312. else:
  6313. plot_container = self.ui.right_layout
  6314. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6315. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6316. self.is_legacy = True
  6317. self.defaults["global_graphic_engine"] = "2D"
  6318. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6319. else:
  6320. try:
  6321. self.plotcanvas = PlotCanvas(plot_container, self)
  6322. except Exception as er:
  6323. msg_txt = traceback.format_exc()
  6324. self.log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6325. self.log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6326. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6327. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6328. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6329. msg += msg_txt
  6330. self.inform.emit(msg)
  6331. return 'fail'
  6332. # So it can receive key presses
  6333. self.plotcanvas.native.setFocus()
  6334. if self.is_legacy is False:
  6335. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6336. # Set the mouse button for panning
  6337. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6338. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6339. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6340. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6341. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6342. # Keys over plot enabled
  6343. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6344. if self.defaults['global_cursor_type'] == 'small':
  6345. self.app_cursor = self.plotcanvas.new_cursor()
  6346. else:
  6347. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6348. if self.ui.grid_snap_btn.isChecked():
  6349. self.app_cursor.enabled = True
  6350. else:
  6351. self.app_cursor.enabled = False
  6352. if self.is_legacy is False:
  6353. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6354. else:
  6355. # will use the default Matplotlib axes
  6356. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6357. def on_zoom_fit(self):
  6358. """
  6359. Callback for zoom-fit request. This can be either from the corresponding
  6360. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6361. with axes limits from the geometry bounds of all objects.
  6362. :return: None
  6363. """
  6364. if self.is_legacy is False:
  6365. self.plotcanvas.fit_view()
  6366. else:
  6367. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6368. width = xmax - xmin
  6369. height = ymax - ymin
  6370. xmin -= 0.05 * width
  6371. xmax += 0.05 * width
  6372. ymin -= 0.05 * height
  6373. ymax += 0.05 * height
  6374. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6375. def on_zoom_in(self):
  6376. """
  6377. Callback for zoom-in request.
  6378. :return:
  6379. """
  6380. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6381. def on_zoom_out(self):
  6382. """
  6383. Callback for zoom-out request.
  6384. :return:
  6385. """
  6386. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6387. def disable_all_plots(self):
  6388. self.defaults.report_usage("disable_all_plots()")
  6389. self.disable_plots(self.collection.get_list())
  6390. self.inform.emit('[success] %s' % _("All plots disabled."))
  6391. def disable_other_plots(self):
  6392. self.defaults.report_usage("disable_other_plots()")
  6393. self.disable_plots(self.collection.get_non_selected())
  6394. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6395. def enable_all_plots(self):
  6396. self.defaults.report_usage("enable_all_plots()")
  6397. self.enable_plots(self.collection.get_list())
  6398. self.inform.emit('[success] %s' % _("All plots enabled."))
  6399. def enable_other_plots(self):
  6400. self.defaults.report_usage("enable_other_plots()")
  6401. self.enable_plots(self.collection.get_non_selected())
  6402. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6403. def on_enable_sel_plots(self):
  6404. self.log.debug("App.on_enable_sel_plot()")
  6405. object_list = self.collection.get_selected()
  6406. self.enable_plots(objects=object_list)
  6407. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6408. def on_disable_sel_plots(self):
  6409. self.log.debug("App.on_disable_sel_plot()")
  6410. # self.inform.emit(_("Disabling plots ..."))
  6411. object_list = self.collection.get_selected()
  6412. self.disable_plots(objects=object_list)
  6413. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6414. def enable_plots(self, objects):
  6415. """
  6416. Enable plots
  6417. :param objects: list of Objects to be enabled
  6418. :return:
  6419. """
  6420. self.log.debug("Enabling plots ...")
  6421. # self.inform.emit(_("Working ..."))
  6422. for obj in objects:
  6423. if obj.options['plot'] is False:
  6424. obj.options.set_change_callback(lambda x: None)
  6425. obj.options['plot'] = True
  6426. try:
  6427. # only the Gerber obj has on_plot_cb_click() method
  6428. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6429. # disable this cb while disconnected,
  6430. # in case the operation takes time the user is not allowed to change it
  6431. obj.ui.plot_cb.setDisabled(True)
  6432. except AttributeError:
  6433. pass
  6434. obj.set_form_item("plot")
  6435. try:
  6436. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6437. obj.ui.plot_cb.setDisabled(False)
  6438. except AttributeError:
  6439. pass
  6440. obj.options.set_change_callback(obj.on_options_change)
  6441. self.collection.update_view()
  6442. def worker_task(objs):
  6443. with self.proc_container.new(_("Enabling plots ...")):
  6444. for plot_obj in objs:
  6445. # obj.options['plot'] = True
  6446. if isinstance(plot_obj, CNCJobObject):
  6447. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6448. else:
  6449. plot_obj.plot(visible=True)
  6450. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6451. def disable_plots(self, objects):
  6452. """
  6453. Disables plots
  6454. :param objects: list of Objects to be disabled
  6455. :return:
  6456. """
  6457. self.log.debug("Disabling plots ...")
  6458. # self.inform.emit(_("Working ..."))
  6459. for obj in objects:
  6460. if obj.options['plot'] is True:
  6461. obj.options.set_change_callback(lambda x: None)
  6462. obj.options['plot'] = False
  6463. try:
  6464. # only the Gerber obj has on_plot_cb_click() method
  6465. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6466. obj.ui.plot_cb.setDisabled(True)
  6467. except AttributeError:
  6468. pass
  6469. obj.set_form_item("plot")
  6470. try:
  6471. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6472. obj.ui.plot_cb.setDisabled(False)
  6473. except AttributeError:
  6474. pass
  6475. obj.options.set_change_callback(obj.on_options_change)
  6476. try:
  6477. self.delete_selection_shape()
  6478. except Exception as e:
  6479. self.log.debug("App.disable_plots() --> %s" % str(e))
  6480. self.collection.update_view()
  6481. def worker_task(objs):
  6482. with self.proc_container.new(_("Disabling plots ...")):
  6483. for plot_obj in objs:
  6484. # obj.options['plot'] = True
  6485. if isinstance(plot_obj, CNCJobObject):
  6486. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6487. else:
  6488. plot_obj.plot(visible=False)
  6489. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6490. def toggle_plots(self, objects):
  6491. """
  6492. Toggle plots visibility
  6493. :param objects: list of Objects for which to be toggled the visibility
  6494. :return: None
  6495. """
  6496. # if no objects selected then do nothing
  6497. if not self.collection.get_selected():
  6498. return
  6499. self.log.debug("Toggling plots ...")
  6500. self.inform.emit(_("Working ..."))
  6501. for obj in objects:
  6502. if obj.options['plot'] is False:
  6503. obj.options['plot'] = True
  6504. else:
  6505. obj.options['plot'] = False
  6506. self.app_obj.plots_updated.emit()
  6507. def clear_plots(self):
  6508. """
  6509. Clear the plots
  6510. :return: None
  6511. """
  6512. objects = self.collection.get_list()
  6513. for obj in objects:
  6514. obj.clear(obj == objects[-1])
  6515. # Clear pool to free memory
  6516. self.clear_pool()
  6517. def on_set_color_action_triggered(self):
  6518. """
  6519. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6520. :return:
  6521. """
  6522. new_color = self.defaults['gerber_plot_fill']
  6523. clicked_action = self.sender()
  6524. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6525. act_name = clicked_action.text()
  6526. sel_obj_list = self.collection.get_selected()
  6527. if not sel_obj_list:
  6528. return
  6529. # a default value, I just chose this one
  6530. alpha_level = 'BF'
  6531. for sel_obj in sel_obj_list:
  6532. if sel_obj.kind == 'excellon':
  6533. alpha_level = str(hex(
  6534. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6535. elif sel_obj.kind == 'gerber':
  6536. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6537. elif sel_obj.kind == 'geometry':
  6538. alpha_level = 'FF'
  6539. else:
  6540. self.log.debug(
  6541. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6542. continue
  6543. sel_obj.alpha_level = alpha_level
  6544. if act_name == _('Red'):
  6545. new_color = '#FF0000' + alpha_level
  6546. if act_name == _('Blue'):
  6547. new_color = '#0000FF' + alpha_level
  6548. if act_name == _('Yellow'):
  6549. new_color = '#FFDF00' + alpha_level
  6550. if act_name == _('Green'):
  6551. new_color = '#00FF00' + alpha_level
  6552. if act_name == _('Purple'):
  6553. new_color = '#FF00FF' + alpha_level
  6554. if act_name == _('Brown'):
  6555. new_color = '#A52A2A' + alpha_level
  6556. if act_name == _('White'):
  6557. new_color = '#FFFFFF' + alpha_level
  6558. if act_name == _('Black'):
  6559. new_color = '#000000' + alpha_level
  6560. if act_name == _('Custom'):
  6561. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6562. c_dialog = QtWidgets.QColorDialog()
  6563. plot_fill_color = c_dialog.getColor(initial=new_color)
  6564. if plot_fill_color.isValid() is False:
  6565. return
  6566. new_color = str(plot_fill_color.name()) + alpha_level
  6567. if act_name == _("Default"):
  6568. for sel_obj in sel_obj_list:
  6569. if sel_obj.kind == 'excellon':
  6570. new_color = self.defaults['excellon_plot_fill']
  6571. new_line_color = self.defaults['excellon_plot_line']
  6572. elif sel_obj.kind == 'gerber':
  6573. new_color = self.defaults['gerber_plot_fill']
  6574. new_line_color = self.defaults['gerber_plot_line']
  6575. elif sel_obj.kind == 'geometry':
  6576. new_color = self.defaults['geometry_plot_line']
  6577. new_line_color = self.defaults['geometry_plot_line']
  6578. else:
  6579. self.log.debug(
  6580. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6581. continue
  6582. sel_obj.fill_color = new_color
  6583. sel_obj.outline_color = new_line_color
  6584. sel_obj.shapes.redraw(
  6585. update_colors=(new_color, new_line_color)
  6586. )
  6587. return
  6588. if act_name == _("Opacity"):
  6589. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6590. # '%s:' % _("Value"),
  6591. # min=0, max=255, step=1, value=191)
  6592. alpha_dialog = FCInputDialogSlider(
  6593. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6594. alpha_level, ok_button = alpha_dialog.get_results()
  6595. if ok_button:
  6596. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6597. for sel_obj in sel_obj_list:
  6598. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6599. sel_obj.shapes.redraw(
  6600. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6601. )
  6602. return
  6603. new_line_color = color_variant(new_color[:7], 0.7)
  6604. if act_name == _("White"):
  6605. new_line_color = color_variant("#dedede", 0.7)
  6606. for sel_obj in sel_obj_list:
  6607. sel_obj.fill_color = new_color
  6608. sel_obj.outline_color = new_line_color
  6609. sel_obj.shapes.redraw(
  6610. update_colors=(new_color, new_line_color)
  6611. )
  6612. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6613. group = self.collection.group_items["gerber"]
  6614. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6615. new_c = (new_line_color, new_color)
  6616. for sel_obj in sel_obj_list:
  6617. if sel_obj.kind == 'gerber':
  6618. item = sel_obj.item
  6619. item_index = self.collection.index(item.row(), 0, group_index)
  6620. idx = item_index.row()
  6621. self.defaults["gerber_color_list"][idx] = new_c
  6622. def generate_cnc_job(self, objects):
  6623. """
  6624. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6625. :param objects: Selected objects in the Project Tab
  6626. :return:
  6627. """
  6628. self.defaults.report_usage("generate_cnc_job()")
  6629. # for obj in objects:
  6630. # obj.generatecncjob()
  6631. for obj in objects:
  6632. obj.on_generatecnc_button_click()
  6633. def start_delayed_quit(self, delay, filename, should_quit=None):
  6634. """
  6635. :param delay: period of checking if project file size is more than zero; in seconds
  6636. :param filename: the name of the project file to be checked periodically for size more than zero
  6637. :param should_quit: if the task finished will be followed by an app quit; boolean
  6638. :return:
  6639. """
  6640. to_quit = should_quit
  6641. self.save_timer = QtCore.QTimer()
  6642. self.save_timer.setInterval(delay)
  6643. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6644. self.save_timer.start()
  6645. def check_project_file_size(self, filename, should_quit=None):
  6646. """
  6647. :param filename: the name of the project file to be checked periodically for size more than zero
  6648. :param should_quit: will quit the app if True; boolean
  6649. :return:
  6650. """
  6651. try:
  6652. if os.stat(filename).st_size > 0:
  6653. self.save_in_progress = False
  6654. self.save_timer.stop()
  6655. if should_quit:
  6656. self.app_quit.emit()
  6657. except Exception:
  6658. traceback.print_exc()
  6659. def save_project_auto(self):
  6660. """
  6661. Called periodically to save the project.
  6662. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  6663. # progress.
  6664. :return:
  6665. """
  6666. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6667. self.on_file_saveproject()
  6668. def save_project_auto_update(self):
  6669. """
  6670. Update the auto save time interval value.
  6671. :return:
  6672. """
  6673. self.log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6674. try:
  6675. if self.autosave_timer.isActive():
  6676. self.autosave_timer.stop()
  6677. except Exception:
  6678. pass
  6679. if self.defaults['global_autosave'] is True:
  6680. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6681. self.autosave_timer.start()
  6682. def on_options_app2project(self):
  6683. """
  6684. Callback for Options->Transfer Options->App=>Project. Copies options
  6685. from application defaults to project defaults.
  6686. :return: None
  6687. """
  6688. self.defaults.report_usage("on_options_app2project")
  6689. self.preferencesUiManager.defaults_read_form()
  6690. self.options.update(self.defaults)
  6691. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6692. """
  6693. Shows a message on the FlatCAM Shell
  6694. :param new_line:
  6695. :param msg: Message to display.
  6696. :param show: Opens the shell.
  6697. :param error: Shows the message as an error.
  6698. :param warning: Shows the message as an warning.
  6699. :param success: Shows the message as an success.
  6700. :param selected: Indicate that something was selected on canvas
  6701. :return: None
  6702. """
  6703. end = '\n' if new_line is True else ''
  6704. if show:
  6705. self.ui.shell_dock.show()
  6706. try:
  6707. if error:
  6708. self.shell.append_error(msg + end)
  6709. elif warning:
  6710. self.shell.append_warning(msg + end)
  6711. elif success:
  6712. self.shell.append_success(msg + end)
  6713. elif selected:
  6714. self.shell.append_selected(msg + end)
  6715. else:
  6716. self.shell.append_output(msg + end)
  6717. except AttributeError:
  6718. self.log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6719. def dec_format(self, val, dec=None):
  6720. """
  6721. Returns a formatted float value with a certain number of decimals
  6722. """
  6723. dec_nr = dec if dec is not None else self.decimals
  6724. return float('%.*f' % (dec_nr, val))
  6725. class ArgsThread(QtCore.QObject):
  6726. open_signal = pyqtSignal(list)
  6727. start = pyqtSignal()
  6728. stop = pyqtSignal()
  6729. if sys.platform == 'win32':
  6730. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6731. else:
  6732. address = ('/tmp/testipc', 'AF_UNIX')
  6733. def __init__(self):
  6734. super().__init__()
  6735. self.listener = None
  6736. self.thread_exit = False
  6737. self.start.connect(self.run)
  6738. self.stop.connect(self.close_listener)
  6739. def my_loop(self, address):
  6740. try:
  6741. self.listener = Listener(*address)
  6742. while self.thread_exit is False:
  6743. conn = self.listener.accept()
  6744. self.serve(conn)
  6745. except socket.error:
  6746. try:
  6747. conn = Client(*address)
  6748. conn.send(sys.argv)
  6749. conn.send('close')
  6750. # close the current instance only if there are args
  6751. if len(sys.argv) > 1:
  6752. try:
  6753. self.listener.close()
  6754. except Exception:
  6755. pass
  6756. sys.exit()
  6757. except ConnectionRefusedError:
  6758. if sys.platform == 'win32':
  6759. pass
  6760. else:
  6761. os.system('rm /tmp/testipc')
  6762. self.listener = Listener(*address)
  6763. while True:
  6764. conn = self.listener.accept()
  6765. self.serve(conn)
  6766. def serve(self, conn):
  6767. while self.thread_exit is False:
  6768. msg = conn.recv()
  6769. if msg == 'close':
  6770. break
  6771. self.open_signal.emit(msg)
  6772. conn.close()
  6773. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6774. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6775. @pyqtSlot()
  6776. def run(self):
  6777. self.my_loop(self.address)
  6778. @pyqtSlot()
  6779. def close_listener(self):
  6780. self.thread_exit = True
  6781. self.listener.close()
  6782. class MenuFileHandlers(QtCore.QObject):
  6783. def __init__(self, app):
  6784. super().__init__()
  6785. self.app = app
  6786. self.inform = self.app.inform
  6787. self.splash = self.app.splash
  6788. self.worker_task = self.app.worker_task
  6789. self.defaults = self.app.defaults
  6790. self.pagesize = {}
  6791. def on_fileopengerber(self, signal, name=None):
  6792. """
  6793. File menu callback for opening a Gerber.
  6794. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6795. :param name:
  6796. :return: None
  6797. """
  6798. self.app.log.debug("on_fileopengerber()")
  6799. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6800. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6801. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6802. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6803. "*.outline);;" \
  6804. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6805. "*.mil);;" \
  6806. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6807. "Allegro Files (*.art);;" \
  6808. "Mentor Files (*.pho *.gdo);;" \
  6809. "All Files (*.*)"
  6810. if name is None:
  6811. try:
  6812. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6813. directory=self.app.get_last_folder(),
  6814. filter=_filter_,
  6815. initialFilter=self.app.last_op_gerber_filter)
  6816. except TypeError:
  6817. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6818. filenames = [str(filename) for filename in filenames]
  6819. self.app.last_op_gerber_filter = _f
  6820. else:
  6821. filenames = [name]
  6822. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6823. "Canvas initialization finished in"),
  6824. '%.2f' % self.app.used_time,
  6825. _("Opening Gerber file.")),
  6826. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6827. color=QtGui.QColor("gray"))
  6828. if len(filenames) == 0:
  6829. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6830. else:
  6831. for filename in filenames:
  6832. if filename != '':
  6833. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6834. def on_fileopenexcellon(self, signal, name=None):
  6835. """
  6836. File menu callback for opening an Excellon file.
  6837. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6838. :param name:
  6839. :return: None
  6840. """
  6841. self.app.log.debug("on_fileopenexcellon()")
  6842. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6843. "All Files (*.*)"
  6844. if name is None:
  6845. try:
  6846. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6847. directory=self.app.get_last_folder(),
  6848. filter=_filter_,
  6849. initialFilter=self.app.last_op_excellon_filter)
  6850. except TypeError:
  6851. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6852. filenames = [str(filename) for filename in filenames]
  6853. self.app.last_op_excellon_filter = _f
  6854. else:
  6855. filenames = [str(name)]
  6856. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6857. "Canvas initialization finished in"),
  6858. '%.2f' % self.app.used_time,
  6859. _("Opening Excellon file.")),
  6860. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6861. color=QtGui.QColor("gray"))
  6862. if len(filenames) == 0:
  6863. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6864. else:
  6865. for filename in filenames:
  6866. if filename != '':
  6867. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6868. def on_fileopengcode(self, signal, name=None):
  6869. """
  6870. File menu call back for opening gcode.
  6871. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6872. :param name:
  6873. :return:
  6874. """
  6875. self.app.log.debug("on_fileopengcode()")
  6876. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6877. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6878. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6879. "All Files (*.*)"
  6880. if name is None:
  6881. try:
  6882. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6883. directory=self.app.get_last_folder(),
  6884. filter=_filter_,
  6885. initialFilter=self.app.last_op_gcode_filter)
  6886. except TypeError:
  6887. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6888. filenames = [str(filename) for filename in filenames]
  6889. self.app.last_op_gcode_filter = _f
  6890. else:
  6891. filenames = [name]
  6892. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6893. "Canvas initialization finished in"),
  6894. '%.2f' % self.app.used_time,
  6895. _("Opening G-Code file.")),
  6896. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6897. color=QtGui.QColor("gray"))
  6898. if len(filenames) == 0:
  6899. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6900. else:
  6901. for filename in filenames:
  6902. if filename != '':
  6903. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6904. def on_file_openproject(self, signal):
  6905. """
  6906. File menu callback for opening a project.
  6907. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6908. :return: None
  6909. """
  6910. self.app.log.debug("on_file_openproject()")
  6911. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6912. try:
  6913. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6914. directory=self.app.get_last_folder(), filter=_filter_)
  6915. except TypeError:
  6916. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6917. filename = str(filename)
  6918. if filename == "":
  6919. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6920. else:
  6921. # self.worker_task.emit({'fcn': self.open_project,
  6922. # 'params': [filename]})
  6923. # The above was failing because open_project() is not
  6924. # thread safe. The new_project()
  6925. self.open_project(filename)
  6926. def on_fileopenhpgl2(self, signal, name=None):
  6927. """
  6928. File menu callback for opening a HPGL2.
  6929. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6930. :param name:
  6931. :return: None
  6932. """
  6933. self.app.log.debug("on_fileopenhpgl2()")
  6934. _filter_ = "HPGL2 Files (*.plt);;" \
  6935. "All Files (*.*)"
  6936. if name is None:
  6937. try:
  6938. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6939. directory=self.app.get_last_folder(),
  6940. filter=_filter_)
  6941. except TypeError:
  6942. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6943. filenames = [str(filename) for filename in filenames]
  6944. else:
  6945. filenames = [name]
  6946. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6947. "Canvas initialization finished in"),
  6948. '%.2f' % self.app.used_time,
  6949. _("Opening HPGL2 file.")),
  6950. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6951. color=QtGui.QColor("gray"))
  6952. if len(filenames) == 0:
  6953. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6954. else:
  6955. for filename in filenames:
  6956. if filename != '':
  6957. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6958. def on_file_openconfig(self, signal):
  6959. """
  6960. File menu callback for opening a config file.
  6961. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6962. :return: None
  6963. """
  6964. self.app.log.debug("on_file_openconfig()")
  6965. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6966. try:
  6967. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6968. directory=self.app.data_path, filter=_filter_)
  6969. except TypeError:
  6970. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6971. filter=_filter_)
  6972. if filename == "":
  6973. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6974. else:
  6975. self.open_config_file(filename)
  6976. def on_file_exportsvg(self):
  6977. """
  6978. Callback for menu item File->Export SVG.
  6979. :return: None
  6980. """
  6981. self.app.log.debug("on_file_exportsvg()")
  6982. obj = self.app.collection.get_active()
  6983. if obj is None:
  6984. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  6985. msg = _("Please Select a Geometry object to export")
  6986. msgbox = QtWidgets.QMessageBox()
  6987. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6988. msgbox.setInformativeText(msg)
  6989. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6990. msgbox.setDefaultButton(bt_ok)
  6991. msgbox.exec_()
  6992. return
  6993. # Check for more compatible types and add as required
  6994. if (not isinstance(obj, GeometryObject)
  6995. and not isinstance(obj, GerberObject)
  6996. and not isinstance(obj, CNCJobObject)
  6997. and not isinstance(obj, ExcellonObject)):
  6998. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6999. msgbox = QtWidgets.QMessageBox()
  7000. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7001. msgbox.setInformativeText(msg)
  7002. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7003. msgbox.setDefaultButton(bt_ok)
  7004. msgbox.exec_()
  7005. return
  7006. name = obj.options["name"]
  7007. _filter = "SVG File (*.svg);;All Files (*.*)"
  7008. try:
  7009. filename, _f = FCFileSaveDialog.get_saved_filename(
  7010. caption=_("Export SVG"),
  7011. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  7012. ext_filter=_filter)
  7013. except TypeError:
  7014. filename, _f = FCFileSaveDialog.get_saved_filename(
  7015. caption=_("Export SVG"),
  7016. ext_filter=_filter)
  7017. filename = str(filename)
  7018. if filename == "":
  7019. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7020. return
  7021. else:
  7022. self.export_svg(name, filename)
  7023. if self.defaults["global_open_style"] is False:
  7024. self.app.file_opened.emit("SVG", filename)
  7025. self.app.file_saved.emit("SVG", filename)
  7026. def on_file_exportpng(self):
  7027. self.app.log.debug("on_file_exportpng()")
  7028. date = str(datetime.today()).rpartition('.')[0]
  7029. date = ''.join(c for c in date if c not in ':-')
  7030. date = date.replace(' ', '_')
  7031. data = None
  7032. if self.app.is_legacy is False:
  7033. image = _screenshot(alpha=False)
  7034. data = np.asarray(image)
  7035. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7036. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  7037. return
  7038. filter_ = "PNG File (*.png);;All Files (*.*)"
  7039. try:
  7040. filename, _f = FCFileSaveDialog.get_saved_filename(
  7041. caption=_("Export PNG Image"),
  7042. directory=self.app.get_last_save_folder() + '/png_' + date,
  7043. ext_filter=filter_)
  7044. except TypeError:
  7045. filename, _f = FCFileSaveDialog.get_saved_filename(
  7046. caption=_("Export PNG Image"),
  7047. ext_filter=filter_)
  7048. filename = str(filename)
  7049. if filename == "":
  7050. self.inform.emit(_("Cancelled."))
  7051. return
  7052. else:
  7053. if self.app.is_legacy is False:
  7054. write_png(filename, data)
  7055. else:
  7056. self.app.plotcanvas.figure.savefig(filename)
  7057. if self.defaults["global_open_style"] is False:
  7058. self.app.file_opened.emit("png", filename)
  7059. self.app.file_saved.emit("png", filename)
  7060. def on_file_savegerber(self):
  7061. """
  7062. Callback for menu item in Project context menu.
  7063. :return: None
  7064. """
  7065. self.app.log.debug("on_file_savegerber()")
  7066. obj = self.app.collection.get_active()
  7067. if obj is None:
  7068. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7069. return
  7070. # Check for more compatible types and add as required
  7071. if not isinstance(obj, GerberObject):
  7072. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7073. return
  7074. name = self.app.collection.get_active().options["name"]
  7075. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7076. try:
  7077. filename, _f = FCFileSaveDialog.get_saved_filename(
  7078. caption="Save Gerber source file",
  7079. directory=self.app.get_last_save_folder() + '/' + name,
  7080. ext_filter=_filter)
  7081. except TypeError:
  7082. filename, _f = FCFileSaveDialog.get_saved_filename(
  7083. caption=_("Save Gerber source file"),
  7084. ext_filter=_filter)
  7085. filename = str(filename)
  7086. if filename == "":
  7087. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7088. return
  7089. else:
  7090. self.save_source_file(name, filename)
  7091. if self.defaults["global_open_style"] is False:
  7092. self.app.file_opened.emit("Gerber", filename)
  7093. self.app.file_saved.emit("Gerber", filename)
  7094. def on_file_savescript(self):
  7095. """
  7096. Callback for menu item in Project context menu.
  7097. :return: None
  7098. """
  7099. self.app.log.debug("on_file_savescript()")
  7100. obj = self.app.collection.get_active()
  7101. if obj is None:
  7102. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7103. return
  7104. # Check for more compatible types and add as required
  7105. if not isinstance(obj, ScriptObject):
  7106. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  7107. return
  7108. name = self.app.collection.get_active().options["name"]
  7109. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7110. try:
  7111. filename, _f = FCFileSaveDialog.get_saved_filename(
  7112. caption="Save Script source file",
  7113. directory=self.app.get_last_save_folder() + '/' + name,
  7114. ext_filter=_filter)
  7115. except TypeError:
  7116. filename, _f = FCFileSaveDialog.get_saved_filename(
  7117. caption=_("Save Script source file"),
  7118. ext_filter=_filter)
  7119. filename = str(filename)
  7120. if filename == "":
  7121. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7122. return
  7123. else:
  7124. self.save_source_file(name, filename)
  7125. if self.defaults["global_open_style"] is False:
  7126. self.app.file_opened.emit("Script", filename)
  7127. self.app.file_saved.emit("Script", filename)
  7128. def on_file_savedocument(self):
  7129. """
  7130. Callback for menu item in Project context menu.
  7131. :return: None
  7132. """
  7133. self.app.log.debug("on_file_savedocument()")
  7134. obj = self.app.collection.get_active()
  7135. if obj is None:
  7136. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7137. return
  7138. # Check for more compatible types and add as required
  7139. if not isinstance(obj, ScriptObject):
  7140. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  7141. return
  7142. name = self.app.collection.get_active().options["name"]
  7143. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7144. try:
  7145. filename, _f = FCFileSaveDialog.get_saved_filename(
  7146. caption="Save Document source file",
  7147. directory=self.app.get_last_save_folder() + '/' + name,
  7148. ext_filter=_filter)
  7149. except TypeError:
  7150. filename, _f = FCFileSaveDialog.get_saved_filename(
  7151. caption=_("Save Document source file"),
  7152. ext_filter=_filter)
  7153. filename = str(filename)
  7154. if filename == "":
  7155. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7156. return
  7157. else:
  7158. self.save_source_file(name, filename)
  7159. if self.defaults["global_open_style"] is False:
  7160. self.app.file_opened.emit("Document", filename)
  7161. self.app.file_saved.emit("Document", filename)
  7162. def on_file_saveexcellon(self):
  7163. """
  7164. Callback for menu item in project context menu.
  7165. :return: None
  7166. """
  7167. self.app.log.debug("on_file_saveexcellon()")
  7168. obj = self.app.collection.get_active()
  7169. if obj is None:
  7170. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7171. return
  7172. # Check for more compatible types and add as required
  7173. if not isinstance(obj, ExcellonObject):
  7174. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7175. return
  7176. name = self.app.collection.get_active().options["name"]
  7177. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7178. try:
  7179. filename, _f = FCFileSaveDialog.get_saved_filename(
  7180. caption=_("Save Excellon source file"),
  7181. directory=self.app.get_last_save_folder() + '/' + name,
  7182. ext_filter=_filter)
  7183. except TypeError:
  7184. filename, _f = FCFileSaveDialog.get_saved_filename(
  7185. caption=_("Save Excellon source file"), ext_filter=_filter)
  7186. filename = str(filename)
  7187. if filename == "":
  7188. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7189. return
  7190. else:
  7191. self.save_source_file(name, filename)
  7192. if self.defaults["global_open_style"] is False:
  7193. self.app.file_opened.emit("Excellon", filename)
  7194. self.app.file_saved.emit("Excellon", filename)
  7195. def on_file_exportexcellon(self):
  7196. """
  7197. Callback for menu item File->Export->Excellon.
  7198. :return: None
  7199. """
  7200. self.app.log.debug("on_file_exportexcellon()")
  7201. obj = self.app.collection.get_active()
  7202. if obj is None:
  7203. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7204. return
  7205. # Check for more compatible types and add as required
  7206. if not isinstance(obj, ExcellonObject):
  7207. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7208. return
  7209. name = self.app.collection.get_active().options["name"]
  7210. _filter = self.defaults["excellon_save_filters"]
  7211. try:
  7212. filename, _f = FCFileSaveDialog.get_saved_filename(
  7213. caption=_("Export Excellon"),
  7214. directory=self.app.get_last_save_folder() + '/' + name,
  7215. ext_filter=_filter)
  7216. except TypeError:
  7217. filename, _f = FCFileSaveDialog.get_saved_filename(
  7218. caption=_("Export Excellon"),
  7219. ext_filter=_filter)
  7220. filename = str(filename)
  7221. if filename == "":
  7222. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7223. return
  7224. else:
  7225. used_extension = filename.rpartition('.')[2]
  7226. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7227. self.export_excellon(name, filename)
  7228. if self.defaults["global_open_style"] is False:
  7229. self.app.file_opened.emit("Excellon", filename)
  7230. self.app.file_saved.emit("Excellon", filename)
  7231. def on_file_exportgerber(self):
  7232. """
  7233. Callback for menu item File->Export->Gerber.
  7234. :return: None
  7235. """
  7236. App.log.debug("on_file_exportgerber()")
  7237. obj = self.app.collection.get_active()
  7238. if obj is None:
  7239. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7240. return
  7241. # Check for more compatible types and add as required
  7242. if not isinstance(obj, GerberObject):
  7243. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7244. return
  7245. name = self.app.collection.get_active().options["name"]
  7246. _filter_ = self.defaults['gerber_save_filters']
  7247. try:
  7248. filename, _f = FCFileSaveDialog.get_saved_filename(
  7249. caption=_("Export Gerber"),
  7250. directory=self.app.get_last_save_folder() + '/' + name,
  7251. ext_filter=_filter_)
  7252. except TypeError:
  7253. filename, _f = FCFileSaveDialog.get_saved_filename(
  7254. caption=_("Export Gerber"),
  7255. ext_filter=_filter_)
  7256. filename = str(filename)
  7257. if filename == "":
  7258. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7259. return
  7260. else:
  7261. used_extension = filename.rpartition('.')[2]
  7262. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7263. self.export_gerber(name, filename)
  7264. if self.defaults["global_open_style"] is False:
  7265. self.app.file_opened.emit("Gerber", filename)
  7266. self.app.file_saved.emit("Gerber", filename)
  7267. def on_file_exportdxf(self):
  7268. """
  7269. Callback for menu item File->Export DXF.
  7270. :return: None
  7271. """
  7272. App.log.debug("on_file_exportdxf()")
  7273. obj = self.app.collection.get_active()
  7274. if obj is None:
  7275. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7276. msg = _("Please Select a Geometry object to export")
  7277. msgbox = QtWidgets.QMessageBox()
  7278. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7279. msgbox.setInformativeText(msg)
  7280. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7281. msgbox.setDefaultButton(bt_ok)
  7282. msgbox.exec_()
  7283. return
  7284. # Check for more compatible types and add as required
  7285. if not isinstance(obj, GeometryObject):
  7286. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7287. msgbox = QtWidgets.QMessageBox()
  7288. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7289. msgbox.setInformativeText(msg)
  7290. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7291. msgbox.setDefaultButton(bt_ok)
  7292. msgbox.exec_()
  7293. return
  7294. name = self.app.collection.get_active().options["name"]
  7295. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7296. try:
  7297. filename, _f = FCFileSaveDialog.get_saved_filename(
  7298. caption=_("Export DXF"),
  7299. directory=self.app.get_last_save_folder() + '/' + name,
  7300. ext_filter=_filter_)
  7301. except TypeError:
  7302. filename, _f = FCFileSaveDialog.get_saved_filename(
  7303. caption=_("Export DXF"),
  7304. ext_filter=_filter_)
  7305. filename = str(filename)
  7306. if filename == "":
  7307. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7308. return
  7309. else:
  7310. self.export_dxf(name, filename)
  7311. if self.defaults["global_open_style"] is False:
  7312. self.app.file_opened.emit("DXF", filename)
  7313. self.app.file_saved.emit("DXF", filename)
  7314. def on_file_importsvg(self, type_of_obj):
  7315. """
  7316. Callback for menu item File->Import SVG.
  7317. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7318. :type type_of_obj: str
  7319. :return: None
  7320. """
  7321. self.app.log.debug("on_file_importsvg()")
  7322. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7323. try:
  7324. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7325. directory=self.app.get_last_folder(),
  7326. filter=_filter_)
  7327. except TypeError:
  7328. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7329. filter=_filter_)
  7330. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7331. type_of_obj = "geometry"
  7332. filenames = [str(filename) for filename in filenames]
  7333. if len(filenames) == 0:
  7334. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7335. else:
  7336. for filename in filenames:
  7337. if filename != '':
  7338. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7339. def on_file_importdxf(self, type_of_obj):
  7340. """
  7341. Callback for menu item File->Import DXF.
  7342. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7343. :type type_of_obj: str
  7344. :return: None
  7345. """
  7346. self.app.log.debug("on_file_importdxf()")
  7347. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7348. try:
  7349. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7350. directory=self.app.get_last_folder(),
  7351. filter=_filter_)
  7352. except TypeError:
  7353. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7354. filter=_filter_)
  7355. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7356. type_of_obj = "geometry"
  7357. filenames = [str(filename) for filename in filenames]
  7358. if len(filenames) == 0:
  7359. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7360. else:
  7361. for filename in filenames:
  7362. if filename != '':
  7363. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7364. def on_file_new_click(self):
  7365. """
  7366. Callback for menu item File -> New.
  7367. Executed on clicking the Menu -> File -> New Project
  7368. :return:
  7369. """
  7370. if self.app.collection.get_list() and self.app.should_we_save:
  7371. msgbox = QtWidgets.QMessageBox()
  7372. # msgbox.setText("<B>Save changes ...</B>")
  7373. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7374. "Creating a New project will delete them.\n"
  7375. "Do you want to Save the project?"))
  7376. msgbox.setWindowTitle(_("Save changes"))
  7377. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7378. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7379. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7380. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7381. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7382. msgbox.setDefaultButton(bt_yes)
  7383. msgbox.exec_()
  7384. response = msgbox.clickedButton()
  7385. if response == bt_yes:
  7386. self.on_file_saveprojectas()
  7387. elif response == bt_cancel:
  7388. return
  7389. elif response == bt_no:
  7390. self.on_file_new()
  7391. else:
  7392. self.on_file_new()
  7393. self.inform.emit('[success] %s...' % _("New Project created"))
  7394. def on_file_new(self, cli=None):
  7395. """
  7396. Returns the application to its startup state. This method is thread-safe.
  7397. :param cli: Boolean. If True this method was run from command line
  7398. :return: None
  7399. """
  7400. self.defaults.report_usage("on_file_new")
  7401. # Remove everything from memory
  7402. self.app.log.debug("on_file_new()")
  7403. # close any editor that might be open
  7404. if self.app.call_source != 'app':
  7405. self.app.editor2object(cleanup=True)
  7406. # ## EDITOR section
  7407. self.app.geo_editor = AppGeoEditor(self.app)
  7408. self.app.exc_editor = AppExcEditor(self.app)
  7409. self.app.grb_editor = AppGerberEditor(self.app)
  7410. # Clear pool
  7411. self.app.clear_pool()
  7412. for obj in self.app.collection.get_list():
  7413. # delete shapes left drawn from mark shape_collections, if any
  7414. if isinstance(obj, GerberObject):
  7415. try:
  7416. obj.mark_shapes_storage.clear()
  7417. obj.mark_shapes.clear(update=True)
  7418. obj.mark_shapes.enabled = False
  7419. except AttributeError:
  7420. pass
  7421. # also delete annotation shapes, if any
  7422. elif isinstance(obj, CNCJobObject):
  7423. try:
  7424. obj.text_col.enabled = False
  7425. del obj.text_col
  7426. obj.annotation.clear(update=True)
  7427. del obj.annotation
  7428. except AttributeError:
  7429. pass
  7430. # delete the exclusion areas
  7431. self.app.exc_areas.clear_shapes()
  7432. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7433. self.app.shell.init_tcl()
  7434. # delete any selection shape on canvas
  7435. self.app.delete_selection_shape()
  7436. # delete all FlatCAM objects
  7437. self.app.collection.delete_all()
  7438. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7439. self.app.setup_default_properties_tab()
  7440. # Clear project filename
  7441. self.app.project_filename = None
  7442. # Load the application defaults
  7443. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7444. # Re-fresh project options
  7445. self.app.on_options_app2project()
  7446. # Init FlatCAMTools
  7447. self.app.init_tools()
  7448. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7449. if cli is None:
  7450. # we need to go in reverse because once we remove a tab then the index changes
  7451. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7452. # and so on. Therefore the deletion should be done in reverse
  7453. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7454. for index in range(wdg_count, -1, -1):
  7455. try:
  7456. self.app.ui.plot_tab_area.closeTab(index)
  7457. except Exception as e:
  7458. log.debug("App.on_file_new() --> %s" % str(e))
  7459. # # And then add again the Plot Area
  7460. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7461. self.app.ui.plot_tab_area.protectTab(0)
  7462. # take the focus of the Notebook on Project Tab.
  7463. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7464. self.app.ui.set_ui_title(name=_("New Project - Not saved"))
  7465. def on_filenewscript(self, silent=False):
  7466. """
  7467. Will create a new script file and open it in the Code Editor
  7468. :param silent: if True will not display status messages
  7469. :return: None
  7470. """
  7471. if silent is False:
  7472. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7473. # hide coordinates toolbars in the infobar while in DB
  7474. self.app.ui.coords_toolbar.hide()
  7475. self.app.ui.delta_coords_toolbar.hide()
  7476. self.app.app_obj.new_script_object()
  7477. def on_fileopenscript(self, name=None, silent=False):
  7478. """
  7479. Will open a Tcl script file into the Code Editor
  7480. :param silent: if True will not display status messages
  7481. :param name: name of a Tcl script file to open
  7482. :return: None
  7483. """
  7484. self.app.log.debug("on_fileopenscript()")
  7485. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7486. "All Files (*.*)"
  7487. if name:
  7488. filenames = [name]
  7489. else:
  7490. try:
  7491. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7492. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7493. except TypeError:
  7494. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7495. if len(filenames) == 0:
  7496. if silent is False:
  7497. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7498. else:
  7499. for filename in filenames:
  7500. if filename != '':
  7501. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7502. def on_fileopenscript_example(self, name=None, silent=False):
  7503. """
  7504. Will open a Tcl script file into the Code Editor
  7505. :param silent: if True will not display status messages
  7506. :param name: name of a Tcl script file to open
  7507. :return:
  7508. """
  7509. self.app.log.debug("on_fileopenscript_example()")
  7510. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7511. "All Files (*.*)"
  7512. # test if the app was frozen and choose the path for the configuration file
  7513. if getattr(sys, "frozen", False) is True:
  7514. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7515. else:
  7516. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7517. if name:
  7518. filenames = [name]
  7519. else:
  7520. try:
  7521. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7522. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7523. except TypeError:
  7524. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7525. if len(filenames) == 0:
  7526. if silent is False:
  7527. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7528. else:
  7529. for filename in filenames:
  7530. if filename != '':
  7531. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7532. def on_filerunscript(self, name=None, silent=False):
  7533. """
  7534. File menu callback for loading and running a TCL script.
  7535. :param silent: if True will not display status messages
  7536. :param name: name of a Tcl script file to be run by FlatCAM
  7537. :return: None
  7538. """
  7539. self.app.log.debug("on_file_runscript()")
  7540. if name:
  7541. filename = name
  7542. if self.app.cmd_line_headless != 1:
  7543. self.splash.showMessage('%s: %ssec\n%s' %
  7544. (_("Canvas initialization started.\n"
  7545. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7546. _("Executing ScriptObject file.")
  7547. ),
  7548. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7549. color=QtGui.QColor("gray"))
  7550. else:
  7551. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7552. "All Files (*.*)"
  7553. try:
  7554. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7555. directory=self.app.get_last_folder(),
  7556. filter=_filter_)
  7557. except TypeError:
  7558. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7559. # The Qt methods above will return a QString which can cause problems later.
  7560. # So far json.dump() will fail to serialize it.
  7561. filename = str(filename)
  7562. if filename == "":
  7563. if silent is False:
  7564. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7565. else:
  7566. if self.app.cmd_line_headless != 1:
  7567. if self.app.ui.shell_dock.isHidden():
  7568. self.app.ui.shell_dock.show()
  7569. try:
  7570. with open(filename, "r") as tcl_script:
  7571. cmd_line_shellfile_content = tcl_script.read()
  7572. if self.app.cmd_line_headless != 1:
  7573. self.app.shell.exec_command(cmd_line_shellfile_content)
  7574. else:
  7575. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7576. if silent is False:
  7577. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7578. except Exception as e:
  7579. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7580. sys.exit(2)
  7581. def on_file_saveproject(self, silent=False):
  7582. """
  7583. Callback for menu item File->Save Project. Saves the project to
  7584. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7585. if set to None. The project is saved by calling ``self.save_project()``.
  7586. :param silent: if True will not display status messages
  7587. :return: None
  7588. """
  7589. if self.app.project_filename is None:
  7590. self.on_file_saveprojectas()
  7591. else:
  7592. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7593. if self.defaults["global_open_style"] is False:
  7594. self.app.file_opened.emit("project", self.app.project_filename)
  7595. self.app.file_saved.emit("project", self.app.project_filename)
  7596. self.app.ui.set_ui_title(name=self.app.project_filename)
  7597. self.app.should_we_save = False
  7598. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7599. """
  7600. Callback for menu item File->Save Project As... Opens a file
  7601. chooser and saves the project to the given file via
  7602. ``self.save_project()``.
  7603. :param make_copy if to be create a copy of the project; boolean
  7604. :param use_thread: if to be run in a separate thread; boolean
  7605. :param quit_action: if to be followed by quiting the application; boolean
  7606. :return: None
  7607. """
  7608. date = str(datetime.today()).rpartition('.')[0]
  7609. date = ''.join(c for c in date if c not in ':-')
  7610. date = date.replace(' ', '_')
  7611. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7612. try:
  7613. filename, _f = FCFileSaveDialog.get_saved_filename(
  7614. caption=_("Save Project As ..."),
  7615. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7616. proj=_("Project")),
  7617. ext_filter=filter_
  7618. )
  7619. except TypeError:
  7620. filename, _f = FCFileSaveDialog.get_saved_filename(
  7621. caption=_("Save Project As ..."),
  7622. ext_filter=filter_)
  7623. filename = str(filename)
  7624. if filename == '':
  7625. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7626. return
  7627. if use_thread is True:
  7628. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7629. else:
  7630. self.save_project(filename, quit_action)
  7631. # self.save_project(filename)
  7632. if self.defaults["global_open_style"] is False:
  7633. self.app.file_opened.emit("project", filename)
  7634. self.app.file_saved.emit("project", filename)
  7635. if not make_copy:
  7636. self.app.project_filename = filename
  7637. self.app.ui.set_ui_title(name=self.app.project_filename)
  7638. self.app.should_we_save = False
  7639. def on_file_save_objects_pdf(self, use_thread=True):
  7640. date = str(datetime.today()).rpartition('.')[0]
  7641. date = ''.join(c for c in date if c not in ':-')
  7642. date = date.replace(' ', '_')
  7643. try:
  7644. obj_selection = self.app.collection.get_selected()
  7645. if len(obj_selection) == 1:
  7646. obj_name = str(obj_selection[0].options['name'])
  7647. else:
  7648. obj_name = _("FlatCAM objects print")
  7649. except AttributeError as err:
  7650. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7651. self.inform.emit('[ERROR_NOTCL] %s' % _("No object is selected."))
  7652. return
  7653. if not obj_selection:
  7654. self.inform.emit('[ERROR_NOTCL] %s' % _("No object is selected."))
  7655. return
  7656. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7657. try:
  7658. filename, _f = FCFileSaveDialog.get_saved_filename(
  7659. caption=_("Save Object as PDF ..."),
  7660. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7661. obj_name=obj_name,
  7662. date=date),
  7663. ext_filter=filter_
  7664. )
  7665. except TypeError:
  7666. filename, _f = FCFileSaveDialog.get_saved_filename(
  7667. caption=_("Save Object as PDF ..."),
  7668. ext_filter=filter_)
  7669. filename = str(filename)
  7670. if filename == '':
  7671. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7672. return
  7673. if use_thread is True:
  7674. self.app.proc_container.new(_("Printing PDF ..."))
  7675. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7676. else:
  7677. self.save_pdf(filename, obj_selection)
  7678. # self.save_project(filename)
  7679. if self.defaults["global_open_style"] is False:
  7680. self.app.file_opened.emit("pdf", filename)
  7681. self.app.file_saved.emit("pdf", filename)
  7682. def save_pdf(self, file_name, obj_selection):
  7683. p_size = self.defaults['global_workspaceT']
  7684. orientation = self.defaults['global_workspace_orientation']
  7685. color = 'black'
  7686. transparency_level = 1.0
  7687. self.pagesize.update(
  7688. {
  7689. 'Bounds': None,
  7690. 'A0': (841 * mm, 1189 * mm),
  7691. 'A1': (594 * mm, 841 * mm),
  7692. 'A2': (420 * mm, 594 * mm),
  7693. 'A3': (297 * mm, 420 * mm),
  7694. 'A4': (210 * mm, 297 * mm),
  7695. 'A5': (148 * mm, 210 * mm),
  7696. 'A6': (105 * mm, 148 * mm),
  7697. 'A7': (74 * mm, 105 * mm),
  7698. 'A8': (52 * mm, 74 * mm),
  7699. 'A9': (37 * mm, 52 * mm),
  7700. 'A10': (26 * mm, 37 * mm),
  7701. 'B0': (1000 * mm, 1414 * mm),
  7702. 'B1': (707 * mm, 1000 * mm),
  7703. 'B2': (500 * mm, 707 * mm),
  7704. 'B3': (353 * mm, 500 * mm),
  7705. 'B4': (250 * mm, 353 * mm),
  7706. 'B5': (176 * mm, 250 * mm),
  7707. 'B6': (125 * mm, 176 * mm),
  7708. 'B7': (88 * mm, 125 * mm),
  7709. 'B8': (62 * mm, 88 * mm),
  7710. 'B9': (44 * mm, 62 * mm),
  7711. 'B10': (31 * mm, 44 * mm),
  7712. 'C0': (917 * mm, 1297 * mm),
  7713. 'C1': (648 * mm, 917 * mm),
  7714. 'C2': (458 * mm, 648 * mm),
  7715. 'C3': (324 * mm, 458 * mm),
  7716. 'C4': (229 * mm, 324 * mm),
  7717. 'C5': (162 * mm, 229 * mm),
  7718. 'C6': (114 * mm, 162 * mm),
  7719. 'C7': (81 * mm, 114 * mm),
  7720. 'C8': (57 * mm, 81 * mm),
  7721. 'C9': (40 * mm, 57 * mm),
  7722. 'C10': (28 * mm, 40 * mm),
  7723. # American paper sizes
  7724. 'LETTER': (8.5 * inch, 11 * inch),
  7725. 'LEGAL': (8.5 * inch, 14 * inch),
  7726. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7727. # From https://en.wikipedia.org/wiki/Paper_size
  7728. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7729. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7730. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7731. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7732. 'LEDGER': (17 * inch, 11 * inch),
  7733. }
  7734. )
  7735. exported_svg = []
  7736. for obj in obj_selection:
  7737. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7738. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7739. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7740. color = obj.fill_color[:-2]
  7741. transparency_level = obj.fill_color[-2:]
  7742. elif obj.kind.lower() == 'geometry':
  7743. color = self.defaults["global_draw_color"]
  7744. # Change the attributes of the exported SVG
  7745. # We don't need stroke-width
  7746. # We set opacity to maximum
  7747. # We set the colour to WHITE
  7748. root = ET.fromstring(svg_obj)
  7749. for child in root:
  7750. child.set('fill', str(color))
  7751. child.set('opacity', str(transparency_level))
  7752. child.set('stroke', str(color))
  7753. exported_svg.append(ET.tostring(root))
  7754. xmin = Inf
  7755. ymin = Inf
  7756. xmax = -Inf
  7757. ymax = -Inf
  7758. for obj in obj_selection:
  7759. try:
  7760. gxmin, gymin, gxmax, gymax = obj.bounds()
  7761. xmin = min([xmin, gxmin])
  7762. ymin = min([ymin, gymin])
  7763. xmax = max([xmax, gxmax])
  7764. ymax = max([ymax, gymax])
  7765. except Exception as e:
  7766. self.app.log.warning(
  7767. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7768. # Determine bounding area for svg export
  7769. bounds = [xmin, ymin, xmax, ymax]
  7770. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7771. # This contain the measure units
  7772. uom = obj_selection[0].units.lower()
  7773. # Define a boundary around SVG of about 1.0mm (~39mils)
  7774. if uom in "mm":
  7775. boundary = 1.0
  7776. else:
  7777. boundary = 0.0393701
  7778. # Convert everything to strings for use in the xml doc
  7779. svgwidth = str(size[0] + (2 * boundary))
  7780. svgheight = str(size[1] + (2 * boundary))
  7781. minx = str(bounds[0] - boundary)
  7782. miny = str(bounds[1] + boundary + size[1])
  7783. # Add a SVG Header and footer to the svg output from shapely
  7784. # The transform flips the Y Axis so that everything renders
  7785. # properly within svg apps such as inkscape
  7786. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7787. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7788. svg_header += 'width="' + svgwidth + uom + '" '
  7789. svg_header += 'height="' + svgheight + uom + '" '
  7790. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7791. svg_header += '>'
  7792. svg_header += '<g transform="scale(1,-1)">'
  7793. svg_footer = '</g> </svg>'
  7794. svg_elem = str(svg_header)
  7795. for svg_item in exported_svg:
  7796. svg_elem += str(svg_item)
  7797. svg_elem += str(svg_footer)
  7798. # Parse the xml through a xml parser just to add line feeds
  7799. # and to make it look more pretty for the output
  7800. doc = parse_xml_string(svg_elem)
  7801. doc_final = doc.toprettyxml()
  7802. try:
  7803. if self.defaults['units'].upper() == 'IN':
  7804. unit = inch
  7805. else:
  7806. unit = mm
  7807. doc_final = StringIO(doc_final)
  7808. drawing = svg2rlg(doc_final)
  7809. if p_size == 'Bounds':
  7810. renderPDF.drawToFile(drawing, file_name)
  7811. else:
  7812. if orientation == 'p':
  7813. page_size = portrait(self.pagesize[p_size])
  7814. else:
  7815. page_size = landscape(self.pagesize[p_size])
  7816. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7817. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7818. renderPDF.draw(drawing, my_canvas, 0, 0)
  7819. my_canvas.save()
  7820. except Exception as e:
  7821. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7822. return 'fail'
  7823. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7824. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7825. """
  7826. Exports a Geometry Object to an SVG file.
  7827. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7828. :param filename: Path to the SVG file to save to.
  7829. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7830. :return:
  7831. """
  7832. if filename is None:
  7833. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7834. is not None else self.defaults["global_last_folder"]
  7835. self.app.log.debug("export_svg()")
  7836. try:
  7837. obj = self.app.collection.get_by_name(str(obj_name))
  7838. except Exception:
  7839. return 'fail'
  7840. with self.app.proc_container.new(_("Exporting ...")):
  7841. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7842. # Determine bounding area for svg export
  7843. bounds = obj.bounds()
  7844. size = obj.size()
  7845. # Convert everything to strings for use in the xml doc
  7846. svgwidth = str(size[0])
  7847. svgheight = str(size[1])
  7848. minx = str(bounds[0])
  7849. miny = str(bounds[1] - size[1])
  7850. uom = obj.units.lower()
  7851. # Add a SVG Header and footer to the svg output from shapely
  7852. # The transform flips the Y Axis so that everything renders
  7853. # properly within svg apps such as inkscape
  7854. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7855. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7856. svg_header += 'width="' + svgwidth + uom + '" '
  7857. svg_header += 'height="' + svgheight + uom + '" '
  7858. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7859. svg_header += '<g transform="scale(1,-1)">'
  7860. svg_footer = '</g> </svg>'
  7861. svg_elem = svg_header + exported_svg + svg_footer
  7862. # Parse the xml through a xml parser just to add line feeds
  7863. # and to make it look more pretty for the output
  7864. svgcode = parse_xml_string(svg_elem)
  7865. svgcode = svgcode.toprettyxml()
  7866. try:
  7867. with open(filename, 'w') as fp:
  7868. fp.write(svgcode)
  7869. except PermissionError:
  7870. self.inform.emit('[WARNING] %s' %
  7871. _("Permission denied, saving not possible.\n"
  7872. "Most likely another app is holding the file open and not accessible."))
  7873. return 'fail'
  7874. if self.defaults["global_open_style"] is False:
  7875. self.app.file_opened.emit("SVG", filename)
  7876. self.app.file_saved.emit("SVG", filename)
  7877. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7878. def on_import_preferences(self):
  7879. """
  7880. Loads the application default settings from a saved file into
  7881. ``self.defaults`` dictionary.
  7882. :return: None
  7883. """
  7884. self.app.log.debug("App.on_import_preferences()")
  7885. # Show file chooser
  7886. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7887. try:
  7888. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7889. directory=self.app.data_path,
  7890. filter=filter_)
  7891. except TypeError:
  7892. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7893. filter=filter_)
  7894. filename = str(filename)
  7895. if filename == "":
  7896. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7897. return
  7898. # Load in the defaults from the chosen file
  7899. self.defaults.load(filename=filename, inform=self.inform)
  7900. self.app.preferencesUiManager.on_preferences_edited()
  7901. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7902. def on_export_preferences(self):
  7903. """
  7904. Save the defaults dictionary to a file.
  7905. :return: None
  7906. """
  7907. self.app.log.debug("on_export_preferences()")
  7908. # defaults_file_content = None
  7909. # Show file chooser
  7910. date = str(datetime.today()).rpartition('.')[0]
  7911. date = ''.join(c for c in date if c not in ':-')
  7912. date = date.replace(' ', '_')
  7913. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7914. try:
  7915. filename, _f = FCFileSaveDialog.get_saved_filename(
  7916. caption=_("Export FlatCAM Preferences"),
  7917. directory=self.app.data_path + '/preferences_' + date,
  7918. ext_filter=filter__
  7919. )
  7920. except TypeError:
  7921. filename, _f = FCFileSaveDialog.get_saved_filename(
  7922. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7923. filename = str(filename)
  7924. if filename == "":
  7925. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7926. return 'fail'
  7927. # Update options
  7928. self.app.preferencesUiManager.defaults_read_form()
  7929. self.defaults.propagate_defaults()
  7930. # Save update options
  7931. try:
  7932. self.defaults.write(filename=filename)
  7933. except Exception:
  7934. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7935. return
  7936. if self.defaults["global_open_style"] is False:
  7937. self.app.file_opened.emit("preferences", filename)
  7938. self.app.file_saved.emit("preferences", filename)
  7939. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7940. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7941. """
  7942. Exports a Excellon Object to an Excellon file.
  7943. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7944. :param filename: Path to the Excellon file to save to.
  7945. :param local_use:
  7946. :param use_thread: if to be run in a separate thread
  7947. :return:
  7948. """
  7949. if filename is None:
  7950. if self.defaults["global_last_save_folder"]:
  7951. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7952. else:
  7953. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7954. self.app.log.debug("export_excellon()")
  7955. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7956. self.defaults["excellon_exp_decimals"]
  7957. )
  7958. if local_use is None:
  7959. try:
  7960. obj = self.app.collection.get_by_name(str(obj_name))
  7961. except Exception:
  7962. return "Could not retrieve object: %s" % obj_name
  7963. else:
  7964. obj = local_use
  7965. if not isinstance(obj, ExcellonObject):
  7966. self.inform.emit('[ERROR_NOTCL] %s' %
  7967. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7968. return
  7969. # updated units
  7970. eunits = self.defaults["excellon_exp_units"]
  7971. ewhole = self.defaults["excellon_exp_integer"]
  7972. efract = self.defaults["excellon_exp_decimals"]
  7973. ezeros = self.defaults["excellon_exp_zeros"]
  7974. eformat = self.defaults["excellon_exp_format"]
  7975. slot_type = self.defaults["excellon_exp_slot_type"]
  7976. fc_units = self.defaults['units'].upper()
  7977. if fc_units == 'MM':
  7978. factor = 1 if eunits == 'METRIC' else 0.03937
  7979. else:
  7980. factor = 25.4 if eunits == 'METRIC' else 1
  7981. def make_excellon():
  7982. try:
  7983. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7984. header = 'M48\n'
  7985. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7986. (str(self.app.version), str(self.app.version_date))
  7987. header += ';Filename: %s' % str(obj_name) + '\n'
  7988. header += ';Created on : %s' % time_str + '\n'
  7989. if eformat == 'dec':
  7990. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7991. header += eunits + '\n'
  7992. for tool in obj.tools:
  7993. if eunits == 'METRIC':
  7994. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7995. tool=str(tool),
  7996. dec=2)
  7997. else:
  7998. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7999. tool=str(tool),
  8000. dec=4)
  8001. else:
  8002. if ezeros == 'LZ':
  8003. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8004. form='ndec', e_zeros='LZ', factor=factor,
  8005. slot_type=slot_type)
  8006. header += '%s,%s\n' % (eunits, 'LZ')
  8007. header += format_exc
  8008. for tool in obj.tools:
  8009. if eunits == 'METRIC':
  8010. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8011. float(obj.tools[tool]['tooldia']) * factor,
  8012. tool=str(tool),
  8013. dec=2)
  8014. else:
  8015. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8016. float(obj.tools[tool]['tooldia']) * factor,
  8017. tool=str(tool),
  8018. dec=4)
  8019. else:
  8020. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8021. form='ndec', e_zeros='TZ', factor=factor,
  8022. slot_type=slot_type)
  8023. header += '%s,%s\n' % (eunits, 'TZ')
  8024. header += format_exc
  8025. for tool in obj.tools:
  8026. if eunits == 'METRIC':
  8027. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8028. float(obj.tools[tool]['tooldia']) * factor,
  8029. tool=str(tool),
  8030. dec=2)
  8031. else:
  8032. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8033. float(obj.tools[tool]['tooldia']) * factor,
  8034. tool=str(tool),
  8035. dec=4)
  8036. header += '%\n'
  8037. footer = 'M30\n'
  8038. exported_excellon = header
  8039. exported_excellon += excellon_code
  8040. exported_excellon += footer
  8041. if local_use is None:
  8042. try:
  8043. with open(filename, 'w') as fp:
  8044. fp.write(exported_excellon)
  8045. except PermissionError:
  8046. self.inform.emit('[WARNING] %s' %
  8047. _("Permission denied, saving not possible.\n"
  8048. "Most likely another app is holding the file open and not accessible."))
  8049. return 'fail'
  8050. if self.defaults["global_open_style"] is False:
  8051. self.app.file_opened.emit("Excellon", filename)
  8052. self.app.file_saved.emit("Excellon", filename)
  8053. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  8054. else:
  8055. return exported_excellon
  8056. except Exception as e:
  8057. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8058. return 'fail'
  8059. if use_thread is True:
  8060. with self.app.proc_container.new(_("Exporting ...")):
  8061. def job_thread_exc(app_obj):
  8062. ret = make_excellon()
  8063. if ret == 'fail':
  8064. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8065. return
  8066. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8067. else:
  8068. eret = make_excellon()
  8069. if eret == 'fail':
  8070. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8071. return 'fail'
  8072. if local_use is not None:
  8073. return eret
  8074. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8075. """
  8076. Exports a Gerber Object to an Gerber file.
  8077. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8078. :param filename: Path to the Gerber file to save to.
  8079. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8080. When not None, the value will be the actual Gerber object for which to create
  8081. the Gerber code
  8082. :param use_thread: if to be run in a separate thread
  8083. :return:
  8084. """
  8085. if filename is None:
  8086. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8087. is not None else self.defaults["global_last_folder"]
  8088. self.app.log.debug("export_gerber()")
  8089. if local_use is None:
  8090. try:
  8091. obj = self.app.collection.get_by_name(str(obj_name))
  8092. except Exception:
  8093. return 'fail'
  8094. else:
  8095. obj = local_use
  8096. # updated units
  8097. gunits = self.defaults["gerber_exp_units"]
  8098. gwhole = self.defaults["gerber_exp_integer"]
  8099. gfract = self.defaults["gerber_exp_decimals"]
  8100. gzeros = self.defaults["gerber_exp_zeros"]
  8101. fc_units = self.defaults['units'].upper()
  8102. if fc_units == 'MM':
  8103. factor = 1 if gunits == 'MM' else 0.03937
  8104. else:
  8105. factor = 25.4 if gunits == 'MM' else 1
  8106. def make_gerber():
  8107. try:
  8108. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8109. header = 'G04*\n'
  8110. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8111. (str(self.app.version), str(self.app.version_date))
  8112. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8113. header += 'G04 Created on : %s*' % time_str + '\n'
  8114. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8115. header += "%MO{units}*%\n".format(units=gunits)
  8116. for apid in obj.apertures:
  8117. if obj.apertures[apid]['type'] == 'C':
  8118. header += "%ADD{apid}{type},{size}*%\n".format(
  8119. apid=str(apid),
  8120. type='C',
  8121. size=(factor * obj.apertures[apid]['size'])
  8122. )
  8123. elif obj.apertures[apid]['type'] == 'R':
  8124. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8125. apid=str(apid),
  8126. type='R',
  8127. width=(factor * obj.apertures[apid]['width']),
  8128. height=(factor * obj.apertures[apid]['height'])
  8129. )
  8130. elif obj.apertures[apid]['type'] == 'O':
  8131. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8132. apid=str(apid),
  8133. type='O',
  8134. width=(factor * obj.apertures[apid]['width']),
  8135. height=(factor * obj.apertures[apid]['height'])
  8136. )
  8137. header += '\n'
  8138. # obsolete units but some software may need it
  8139. if gunits == 'IN':
  8140. header += 'G70*\n'
  8141. else:
  8142. header += 'G71*\n'
  8143. # Absolute Mode
  8144. header += 'G90*\n'
  8145. header += 'G01*\n'
  8146. # positive polarity
  8147. header += '%LPD*%\n'
  8148. footer = 'M02*\n'
  8149. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8150. exported_gerber = header
  8151. exported_gerber += gerber_code
  8152. exported_gerber += footer
  8153. if local_use is None:
  8154. try:
  8155. with open(filename, 'w') as fp:
  8156. fp.write(exported_gerber)
  8157. except PermissionError:
  8158. self.inform.emit('[WARNING] %s' %
  8159. _("Permission denied, saving not possible.\n"
  8160. "Most likely another app is holding the file open and not accessible."))
  8161. return 'fail'
  8162. if self.defaults["global_open_style"] is False:
  8163. self.app.file_opened.emit("Gerber", filename)
  8164. self.app.file_saved.emit("Gerber", filename)
  8165. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8166. else:
  8167. return exported_gerber
  8168. except Exception as e:
  8169. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8170. return 'fail'
  8171. if use_thread is True:
  8172. with self.app.proc_container.new(_("Exporting ...")):
  8173. def job_thread_grb(app_obj):
  8174. ret = make_gerber()
  8175. if ret == 'fail':
  8176. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8177. return
  8178. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8179. else:
  8180. gret = make_gerber()
  8181. if gret == 'fail':
  8182. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8183. return 'fail'
  8184. if local_use is not None:
  8185. return gret
  8186. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  8187. """
  8188. Exports a Geometry Object to an DXF file.
  8189. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8190. :param filename: Path to the DXF file to save to.
  8191. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8192. When not None, the value will be the actual Geometry object for which to create
  8193. the Geometry/DXF code
  8194. :param use_thread: if to be run in a separate thread
  8195. :return:
  8196. """
  8197. if filename is None:
  8198. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8199. is not None else self.defaults["global_last_folder"]
  8200. self.app.log.debug("export_dxf()")
  8201. if local_use is None:
  8202. try:
  8203. obj = self.app.collection.get_by_name(str(obj_name))
  8204. except Exception:
  8205. return 'fail'
  8206. else:
  8207. obj = local_use
  8208. def make_dxf():
  8209. try:
  8210. dxf_code = obj.export_dxf()
  8211. if local_use is None:
  8212. try:
  8213. dxf_code.saveas(filename)
  8214. except PermissionError:
  8215. self.inform.emit('[WARNING] %s' %
  8216. _("Permission denied, saving not possible.\n"
  8217. "Most likely another app is holding the file open and not accessible."))
  8218. return 'fail'
  8219. if self.defaults["global_open_style"] is False:
  8220. self.app.file_opened.emit("DXF", filename)
  8221. self.app.file_saved.emit("DXF", filename)
  8222. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8223. else:
  8224. return dxf_code
  8225. except Exception as e:
  8226. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8227. return 'fail'
  8228. if use_thread is True:
  8229. with self.app.proc_container.new(_("Exporting ...")):
  8230. def job_thread_exc(app_obj):
  8231. ret_dxf_val = make_dxf()
  8232. if ret_dxf_val == 'fail':
  8233. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export.'))
  8234. return
  8235. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8236. else:
  8237. ret = make_dxf()
  8238. if ret == 'fail':
  8239. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export.'))
  8240. return
  8241. if local_use is not None:
  8242. return ret
  8243. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8244. """
  8245. Adds a new Geometry Object to the projects and populates
  8246. it with shapes extracted from the SVG file.
  8247. :param plot: If True then the resulting object will be plotted on canvas
  8248. :param filename: Path to the SVG file.
  8249. :param geo_type: Type of FlatCAM object that will be created from SVG
  8250. :param outname: The name given to the resulting FlatCAM object
  8251. :return:
  8252. """
  8253. self.app.log.debug("App.import_svg()")
  8254. obj_type = ""
  8255. if geo_type is None or geo_type == "geometry":
  8256. obj_type = "geometry"
  8257. elif geo_type == "gerber":
  8258. obj_type = "gerber"
  8259. else:
  8260. self.inform.emit('[ERROR_NOTCL] %s' %
  8261. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8262. return
  8263. units = self.defaults['units'].upper()
  8264. def obj_init(geo_obj, app_obj):
  8265. geo_obj.import_svg(filename, obj_type, units=units)
  8266. geo_obj.multigeo = True
  8267. with open(filename) as f:
  8268. file_content = f.read()
  8269. geo_obj.source_file = file_content
  8270. # appGUI feedback
  8271. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8272. with self.app.proc_container.new('%s ...' % _("Importing")):
  8273. # Object name
  8274. name = outname or filename.split('/')[-1].split('\\')[-1]
  8275. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8276. if ret == 'fail':
  8277. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8278. return 'fail'
  8279. # Register recent file
  8280. self.app.file_opened.emit("svg", filename)
  8281. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8282. """
  8283. Adds a new Geometry Object to the projects and populates
  8284. it with shapes extracted from the DXF file.
  8285. :param filename: Path to the DXF file.
  8286. :param geo_type: Type of FlatCAM object that will be created from DXF
  8287. :param outname: Name for the imported Geometry
  8288. :param plot: If True then the resulting object will be plotted on canvas
  8289. :return:
  8290. """
  8291. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8292. obj_type = ""
  8293. if geo_type is None or geo_type == "geometry":
  8294. obj_type = "geometry"
  8295. elif geo_type == "gerber":
  8296. obj_type = geo_type
  8297. else:
  8298. self.inform.emit('[ERROR_NOTCL] %s' %
  8299. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8300. return
  8301. units = self.defaults['units'].upper()
  8302. def obj_init(geo_obj, app_obj):
  8303. if obj_type == "geometry":
  8304. geo_obj.import_dxf_as_geo(filename, units=units)
  8305. elif obj_type == "gerber":
  8306. geo_obj.import_dxf_as_gerber(filename, units=units)
  8307. else:
  8308. return "fail"
  8309. geo_obj.multigeo = True
  8310. with open(filename) as f:
  8311. file_content = f.read()
  8312. geo_obj.source_file = file_content
  8313. # appGUI feedback
  8314. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8315. with self.app.proc_container.new('%s ...' % _("Importing")):
  8316. # Object name
  8317. name = outname or filename.split('/')[-1].split('\\')[-1]
  8318. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8319. if ret == 'fail':
  8320. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8321. return 'fail'
  8322. # Register recent file
  8323. self.app.file_opened.emit("dxf", filename)
  8324. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8325. """
  8326. Opens a Gerber file, parses it and creates a new object for
  8327. it in the program. Thread-safe.
  8328. :param outname: Name of the resulting object. None causes the
  8329. name to be that of the file. Str.
  8330. :param filename: Gerber file filename
  8331. :type filename: str
  8332. :param plot: boolean, to plot or not the resulting object
  8333. :param from_tcl: True if run from Tcl Shell
  8334. :return: None
  8335. """
  8336. # How the object should be initialized
  8337. def obj_init(gerber_obj, app_obj):
  8338. assert isinstance(gerber_obj, GerberObject), \
  8339. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8340. # Opening the file happens here
  8341. try:
  8342. gerber_obj.parse_file(filename)
  8343. except IOError:
  8344. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8345. return "fail"
  8346. except ParseError as err:
  8347. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8348. app_obj.log.error(str(err))
  8349. return "fail"
  8350. except Exception as e:
  8351. log.debug("App.open_gerber() --> %s" % str(e))
  8352. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8353. msg += traceback.format_exc()
  8354. app_obj.inform.emit(msg)
  8355. return "fail"
  8356. if gerber_obj.is_empty():
  8357. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8358. _("Object is not Gerber file or empty. Aborting object creation."))
  8359. return "fail"
  8360. self.app.log.debug("open_gerber()")
  8361. with self.app.proc_container.new(_("Opening ...")):
  8362. # Object name
  8363. name = outname or filename.split('/')[-1].split('\\')[-1]
  8364. # # ## Object creation # ##
  8365. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8366. if ret_val == 'fail':
  8367. if from_tcl:
  8368. filename = self.defaults['global_tcl_path'] + '/' + name
  8369. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8370. if ret_val == 'fail':
  8371. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8372. return 'fail'
  8373. # Register recent file
  8374. self.app.file_opened.emit("gerber", filename)
  8375. # appGUI feedback
  8376. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8377. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8378. """
  8379. Opens an Excellon file, parses it and creates a new object for
  8380. it in the program. Thread-safe.
  8381. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8382. :param filename: Excellon file filename
  8383. :type filename: str
  8384. :param plot: boolean, to plot or not the resulting object
  8385. :param from_tcl: True if run from Tcl Shell
  8386. :return: None
  8387. """
  8388. self.app.log.debug("open_excellon()")
  8389. # How the object should be initialized
  8390. def obj_init(excellon_obj, app_obj):
  8391. try:
  8392. ret = excellon_obj.parse_file(filename=filename)
  8393. if ret == "fail":
  8394. app_obj.log.debug("Excellon parsing failed.")
  8395. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8396. return "fail"
  8397. except IOError:
  8398. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8399. app_obj.log.debug("Could not open Excellon object.")
  8400. return "fail"
  8401. except Exception:
  8402. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8403. msg += traceback.format_exc()
  8404. app_obj.inform.emit(msg)
  8405. return "fail"
  8406. ret = excellon_obj.create_geometry()
  8407. if ret == 'fail':
  8408. app_obj.log.debug("Could not create geometry for Excellon object.")
  8409. return "fail"
  8410. for tool in excellon_obj.tools:
  8411. if excellon_obj.tools[tool]['solid_geometry']:
  8412. return
  8413. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8414. return "fail"
  8415. with self.app.proc_container.new(_("Opening ...")):
  8416. # Object name
  8417. name = outname or filename.split('/')[-1].split('\\')[-1]
  8418. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8419. if ret_val == 'fail':
  8420. if from_tcl:
  8421. filename = self.defaults['global_tcl_path'] + '/' + name
  8422. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8423. if ret_val == 'fail':
  8424. self.inform.emit('[ERROR_NOTCL] %s' %
  8425. _('Open Excellon file failed. Probable not an Excellon file.'))
  8426. return
  8427. # Register recent file
  8428. self.app.file_opened.emit("excellon", filename)
  8429. # appGUI feedback
  8430. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8431. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8432. """
  8433. Opens a G-gcode file, parses it and creates a new object for
  8434. it in the program. Thread-safe.
  8435. :param filename: G-code file filename
  8436. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8437. :param force_parsing:
  8438. :param plot: If True plot the object on canvas
  8439. :param from_tcl: True if run from Tcl Shell
  8440. :return: None
  8441. """
  8442. self.app.log.debug("open_gcode()")
  8443. # How the object should be initialized
  8444. def obj_init(job_obj, app_obj_):
  8445. """
  8446. :param job_obj: the resulting object
  8447. :type app_obj_: App
  8448. """
  8449. assert isinstance(app_obj_, App), \
  8450. "Initializer expected App, got %s" % type(app_obj_)
  8451. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8452. try:
  8453. f = open(filename)
  8454. gcode = f.read()
  8455. f.close()
  8456. except IOError:
  8457. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8458. return "fail"
  8459. job_obj.gcode = gcode
  8460. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8461. if gcode_ret == "fail":
  8462. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8463. return "fail"
  8464. job_obj.create_geometry()
  8465. with self.app.proc_container.new(_("Opening ...")):
  8466. # Object name
  8467. name = outname or filename.split('/')[-1].split('\\')[-1]
  8468. # New object creation and file processing
  8469. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8470. if ret_val == 'fail':
  8471. if from_tcl:
  8472. filename = self.defaults['global_tcl_path'] + '/' + name
  8473. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8474. if ret_val == 'fail':
  8475. self.inform.emit('[ERROR_NOTCL] %s' %
  8476. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8477. "Try to load it from File menu.\n "
  8478. "Attempting to create a FlatCAM CNCJob Object from "
  8479. "G-Code file failed during processing"))
  8480. return "fail"
  8481. # Register recent file
  8482. self.app.file_opened.emit("cncjob", filename)
  8483. # appGUI feedback
  8484. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8485. def open_hpgl2(self, filename, outname=None):
  8486. """
  8487. Opens a HPGL2 file, parses it and creates a new object for
  8488. it in the program. Thread-safe.
  8489. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8490. :param filename: HPGL2 file filename
  8491. :return: None
  8492. """
  8493. filename = filename
  8494. # How the object should be initialized
  8495. def obj_init(geo_obj, app_obj):
  8496. assert isinstance(geo_obj, GeometryObject), \
  8497. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8498. # Opening the file happens here
  8499. obj = HPGL2(self.app)
  8500. try:
  8501. HPGL2.parse_file(obj, filename)
  8502. except IOError:
  8503. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8504. return "fail"
  8505. except ParseError as err:
  8506. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8507. app_obj.log.error(str(err))
  8508. return "fail"
  8509. except Exception as e:
  8510. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8511. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8512. msg += traceback.format_exc()
  8513. app_obj.inform.emit(msg)
  8514. return "fail"
  8515. geo_obj.multigeo = True
  8516. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8517. geo_obj.tools = deepcopy(obj.tools)
  8518. geo_obj.source_file = deepcopy(obj.source_file)
  8519. del obj
  8520. if not geo_obj.solid_geometry:
  8521. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8522. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8523. return "fail"
  8524. self.app.log.debug("open_hpgl2()")
  8525. with self.app.proc_container.new(_("Opening ...")):
  8526. # Object name
  8527. name = outname or filename.split('/')[-1].split('\\')[-1]
  8528. # # ## Object creation # ##
  8529. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8530. if ret == 'fail':
  8531. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed. Probable not a HPGL2 file.'))
  8532. return 'fail'
  8533. # Register recent file
  8534. self.app.file_opened.emit("geometry", filename)
  8535. # appGUI feedback
  8536. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8537. def open_script(self, filename, outname=None, silent=False):
  8538. """
  8539. Opens a Script file, parses it and creates a new object for
  8540. it in the program. Thread-safe.
  8541. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8542. :param filename: Script file filename
  8543. :param silent: If True there will be no messages printed to StatusBar
  8544. :return: None
  8545. """
  8546. def obj_init(script_obj, app_obj):
  8547. assert isinstance(script_obj, ScriptObject), \
  8548. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8549. if silent is False:
  8550. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8551. try:
  8552. script_obj.parse_file(filename)
  8553. except IOError:
  8554. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8555. return "fail"
  8556. except ParseError as err:
  8557. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8558. app_obj.log.error(str(err))
  8559. return "fail"
  8560. except Exception as e:
  8561. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8562. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8563. msg += traceback.format_exc()
  8564. app_obj.inform.emit(msg)
  8565. return "fail"
  8566. self.app.log.debug("open_script()")
  8567. with self.app.proc_container.new(_("Opening ...")):
  8568. # Object name
  8569. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8570. # Object creation
  8571. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8572. if ret_val == 'fail':
  8573. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8574. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8575. if ret_val == 'fail':
  8576. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8577. return 'fail'
  8578. # Register recent file
  8579. self.app.file_opened.emit("script", filename)
  8580. # appGUI feedback
  8581. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8582. def open_config_file(self, filename, run_from_arg=None):
  8583. """
  8584. Loads a config file from the specified file.
  8585. :param filename: Name of the file from which to load.
  8586. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8587. :return: None
  8588. """
  8589. self.app.log.debug("Opening config file: " + filename)
  8590. if run_from_arg:
  8591. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8592. "Canvas initialization finished in"),
  8593. '%.2f' % self.app.used_time,
  8594. _("Opening FlatCAM Config file.")),
  8595. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8596. color=QtGui.QColor("gray"))
  8597. # # add the tab if it was closed
  8598. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8599. # # first clear previous text in text editor (if any)
  8600. # self.ui.text_editor_tab.code_editor.clear()
  8601. #
  8602. # # Switch plot_area to CNCJob tab
  8603. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8604. # close the Code editor if already open
  8605. if self.app.toggle_codeeditor:
  8606. self.app.on_toggle_code_editor()
  8607. self.app.on_toggle_code_editor()
  8608. try:
  8609. if filename:
  8610. f = QtCore.QFile(filename)
  8611. if f.open(QtCore.QIODevice.ReadOnly):
  8612. stream = QtCore.QTextStream(f)
  8613. code_edited = stream.readAll()
  8614. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8615. f.close()
  8616. except IOError:
  8617. self.app.log.error("Failed to open config file: %s" % filename)
  8618. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8619. return
  8620. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8621. """
  8622. Loads a project from the specified file.
  8623. 1) Loads and parses file
  8624. 2) Registers the file as recently opened.
  8625. 3) Calls on_file_new()
  8626. 4) Updates options
  8627. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8628. 6) Calls plot_all() if plot=True
  8629. :param filename: Name of the file from which to load.
  8630. :param run_from_arg: True if run for arguments
  8631. :param plot: If True plot all objects in the project
  8632. :param cli: Run from command line
  8633. :param from_tcl: True if run from Tcl Sehll
  8634. :return: None
  8635. """
  8636. self.app.log.debug("Opening project: " + filename)
  8637. # block autosaving while a project is loaded
  8638. self.app.block_autosave = True
  8639. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8640. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8641. if cli is None:
  8642. self.app.ui.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8643. if run_from_arg:
  8644. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8645. "Canvas initialization finished in"),
  8646. '%.2f' % self.app.used_time,
  8647. _("Opening FlatCAM Project file.")),
  8648. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8649. color=QtGui.QColor("gray"))
  8650. # Open and parse an uncompressed Project file
  8651. try:
  8652. f = open(filename, 'r')
  8653. except IOError:
  8654. if from_tcl:
  8655. name = filename.split('/')[-1].split('\\')[-1]
  8656. filename = self.defaults['global_tcl_path'] + '/' + name
  8657. try:
  8658. f = open(filename, 'r')
  8659. except IOError:
  8660. self.app.log.error("Failed to open project file: %s" % filename)
  8661. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8662. return
  8663. else:
  8664. self.app.log.error("Failed to open project file: %s" % filename)
  8665. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8666. return
  8667. try:
  8668. d = json.load(f, object_hook=dict2obj)
  8669. except Exception as e:
  8670. self.app.log.error(
  8671. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8672. (filename, str(e)))
  8673. f.close()
  8674. # Open and parse a compressed Project file
  8675. try:
  8676. with lzma.open(filename) as f:
  8677. file_content = f.read().decode('utf-8')
  8678. d = json.loads(file_content, object_hook=dict2obj)
  8679. except Exception as e:
  8680. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8681. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8682. return
  8683. # Clear the current project
  8684. # # NOT THREAD SAFE # ##
  8685. if run_from_arg is True:
  8686. pass
  8687. elif cli is True:
  8688. self.app.delete_selection_shape()
  8689. else:
  8690. self.on_file_new()
  8691. # Project options
  8692. self.app.options.update(d['options'])
  8693. self.app.project_filename = filename
  8694. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8695. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8696. if cli is None:
  8697. self.app.set_screen_units(self.app.options["units"])
  8698. # Re create objects
  8699. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8700. for obj in d['objs']:
  8701. def obj_init(obj_inst, app_inst):
  8702. try:
  8703. obj_inst.from_dict(obj)
  8704. except Exception as erro:
  8705. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8706. return 'fail'
  8707. self.app.log.debug(
  8708. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8709. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8710. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8711. if cli is None:
  8712. self.app.ui.set_ui_title(name="{} {}: {}".format(
  8713. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8714. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8715. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8716. self.app.should_we_save = False
  8717. self.app.file_opened.emit("project", filename)
  8718. # restore autosaving after a project was loaded
  8719. self.app.block_autosave = False
  8720. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8721. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8722. if cli is None:
  8723. self.app.ui.set_ui_title(name=self.app.project_filename)
  8724. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8725. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8726. """
  8727. Saves the current project to the specified file.
  8728. :param filename: Name of the file in which to save.
  8729. :type filename: str
  8730. :param quit_action: if the project saving will be followed by an app quit; boolean
  8731. :param silent: if True will not display status messages
  8732. :param from_tcl True is run from Tcl Shell
  8733. :return: None
  8734. """
  8735. self.app.log.debug("save_project()")
  8736. self.app.save_in_progress = True
  8737. if from_tcl:
  8738. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8739. with self.app.proc_container.new(_("Saving Project ...")):
  8740. # Capture the latest changes
  8741. # Current object
  8742. try:
  8743. current_object = self.app.collection.get_active()
  8744. if current_object:
  8745. current_object.read_form()
  8746. except Exception as e:
  8747. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8748. # Serialize the whole project
  8749. d = {
  8750. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8751. "options": self.app.options,
  8752. "version": self.app.version
  8753. }
  8754. if self.defaults["global_save_compressed"] is True:
  8755. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8756. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8757. # # Write
  8758. f.write(g)
  8759. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8760. else:
  8761. # Open file
  8762. try:
  8763. f = open(filename, 'w')
  8764. except IOError:
  8765. self.app.log.error("Failed to open file for saving: %s", filename)
  8766. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8767. return
  8768. # Write
  8769. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8770. f.close()
  8771. # verification of the saved project
  8772. # Open and parse
  8773. try:
  8774. saved_f = open(filename, 'r')
  8775. except IOError:
  8776. if silent is False:
  8777. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8778. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8779. return
  8780. try:
  8781. saved_d = json.load(saved_f, object_hook=dict2obj)
  8782. except Exception:
  8783. if silent is False:
  8784. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8785. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8786. f.close()
  8787. return
  8788. saved_f.close()
  8789. if silent is False:
  8790. if 'version' in saved_d:
  8791. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8792. else:
  8793. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8794. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8795. tb_settings = QSettings("Open Source", "FlatCAM")
  8796. lock_state = self.app.ui.lock_action.isChecked()
  8797. tb_settings.setValue('toolbar_lock', lock_state)
  8798. # This will write the setting to the platform specific storage.
  8799. del tb_settings
  8800. # if quit:
  8801. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8802. # t.start()
  8803. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8804. def save_source_file(self, obj_name, filename):
  8805. """
  8806. Exports a FlatCAM Object to an Gerber/Excellon file.
  8807. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8808. :param filename: Path to the Gerber file to save to.
  8809. :return:
  8810. """
  8811. if filename is None:
  8812. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8813. is not None else self.defaults["global_last_folder"]
  8814. self.app.log.debug("save source file()")
  8815. obj = self.app.collection.get_by_name(obj_name)
  8816. file_string = StringIO(obj.source_file)
  8817. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8818. if file_string.getvalue() == '':
  8819. self.inform.emit('[ERROR_NOTCL] %s' %
  8820. _("Save cancelled because source file is empty. Try to export the file."))
  8821. return 'fail'
  8822. try:
  8823. with open(filename, 'w') as file:
  8824. file.writelines('G04*\n')
  8825. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8826. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8827. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8828. file.writelines('G04 Created on : %s*\n' % time_string)
  8829. for line in file_string:
  8830. file.writelines(line)
  8831. except PermissionError:
  8832. self.inform.emit('[WARNING] %s' %
  8833. _("Permission denied, saving not possible.\n"
  8834. "Most likely another app is holding the file open and not accessible."))
  8835. return 'fail'
  8836. def on_file_savedefaults(self):
  8837. """
  8838. Callback for menu item File->Save Defaults. Saves application default options
  8839. ``self.defaults`` to current_defaults.FlatConfig.
  8840. :return: None
  8841. """
  8842. self.app.preferencesUiManager.save_defaults()
  8843. # end of file