app_Main.py 477 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610
  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/10/30"
  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. # declare it here so there is a reference
  224. self.f_handlers = lambda: None
  225. # ############################################################################################################
  226. # ################# Setup the listening thread for another instance launching with args ######################
  227. # ############################################################################################################
  228. if sys.platform == 'win32' or sys.platform == 'linux':
  229. # make sure the thread is stored by using a self. otherwise it's garbage collected
  230. self.listen_th = QtCore.QThread()
  231. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  232. self.new_launch = ArgsThread()
  233. self.new_launch.open_signal[list].connect(self.on_startup_args)
  234. self.new_launch.moveToThread(self.listen_th)
  235. self.new_launch.start.emit()
  236. # ############################################################################################################
  237. # ########################################## OS-specific #####################################################
  238. # ############################################################################################################
  239. portable = False
  240. # Folder for user settings.
  241. if sys.platform == 'win32':
  242. if platform.architecture()[0] == '32bit':
  243. self.log.debug("Win32!")
  244. else:
  245. self.log.debug("Win64!")
  246. # #######################################################################################################
  247. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  248. # #######################################################################################################
  249. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r'):
  252. pass
  253. except FileNotFoundError:
  254. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r') as f:
  257. try:
  258. for line in f:
  259. param = str(line).replace('\n', '').rpartition('=')
  260. if param[0] == 'portable':
  261. try:
  262. portable = eval(param[2])
  263. except NameError:
  264. portable = False
  265. if param[0] == 'headless':
  266. if param[2].lower() == 'true':
  267. self.cmd_line_headless = 1
  268. else:
  269. self.cmd_line_headless = None
  270. except Exception as e:
  271. self.log.debug('App.__init__() -->%s' % str(e))
  272. return
  273. except FileNotFoundError as e:
  274. self.log.debug(str(e))
  275. pass
  276. if portable is False:
  277. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  278. else:
  279. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  280. self.os = 'windows'
  281. else: # Linux/Unix/MacOS
  282. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  283. self.os = 'unix'
  284. # ############################################################################################################
  285. # ################################# Setup folders and files ##################################################
  286. # ############################################################################################################
  287. if not os.path.exists(self.data_path):
  288. os.makedirs(self.data_path)
  289. self.log.debug('Created data folder: ' + self.data_path)
  290. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  291. self.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  292. self.preprocessorpaths = self.preprocessors_path()
  293. if not os.path.exists(self.preprocessorpaths):
  294. os.makedirs(self.preprocessorpaths)
  295. self.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  296. # create tools_db.FlatDB file if there is none
  297. db_path = self.tools_database_path()
  298. try:
  299. f = open(db_path)
  300. f.close()
  301. except IOError:
  302. self.log.debug('Creating empty tools_db.FlatDB')
  303. f = open(db_path, 'w')
  304. json.dump({}, f)
  305. f.close()
  306. # create current_defaults.FlatConfig file if there is none
  307. def_path = self.defaults_path()
  308. try:
  309. f = open(def_path)
  310. f.close()
  311. except IOError:
  312. self.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(def_path, 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # the factory defaults are written only once at the first launch of the application after installation
  317. FlatCAMDefaults.save_factory_defaults(self.factory_defaults_path(), self.version)
  318. # create a recent files json file if there is none
  319. rec_f_path = self.recent_files_path()
  320. try:
  321. f = open(rec_f_path)
  322. f.close()
  323. except IOError:
  324. self.log.debug('Creating empty recent.json')
  325. f = open(rec_f_path, 'w')
  326. json.dump([], f)
  327. f.close()
  328. # create a recent projects json file if there is none
  329. rec_proj_path = self.recent_projects_path()
  330. try:
  331. fp = open(rec_proj_path)
  332. fp.close()
  333. except IOError:
  334. self.log.debug('Creating empty recent_projects.json')
  335. fp = open(rec_proj_path, 'w')
  336. json.dump([], fp)
  337. fp.close()
  338. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  339. # This will fail under cx_freeze ...
  340. self.app_home = os.path.dirname(os.path.realpath(__file__))
  341. self.log.debug("Application path is " + self.app_home)
  342. self.log.debug("Started in " + os.getcwd())
  343. # cx_freeze workaround
  344. if os.path.isfile(self.app_home):
  345. self.app_home = os.path.dirname(self.app_home)
  346. os.chdir(self.app_home)
  347. # ############################################################################################################
  348. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  349. # ############################################################################################################
  350. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  351. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  352. if user_defaults:
  353. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  354. if self.defaults['units'] == 'MM':
  355. self.decimals = int(self.defaults['decimals_metric'])
  356. else:
  357. self.decimals = int(self.defaults['decimals_inch'])
  358. if self.defaults["global_gray_icons"] is False:
  359. self.resource_location = 'assets/resources'
  360. else:
  361. self.resource_location = 'assets/resources/dark_resources'
  362. self.current_units = self.defaults['units']
  363. # ###########################################################################################################
  364. # #################################### SETUP OBJECT CLASSES #################################################
  365. # ###########################################################################################################
  366. self.setup_obj_classes()
  367. # ###########################################################################################################
  368. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  369. # ###########################################################################################################
  370. self.pool = Pool()
  371. # ###########################################################################################################
  372. # ###################################### Clear GUI Settings - once at first start ###########################
  373. # ###########################################################################################################
  374. if self.defaults["first_run"] is True:
  375. # on first run clear the previous QSettings, therefore clearing the GUI settings
  376. qsettings = QSettings("Open Source", "FlatCAM")
  377. for key in qsettings.allKeys():
  378. qsettings.remove(key)
  379. # This will write the setting to the platform specific storage.
  380. del qsettings
  381. # ###########################################################################################################
  382. # ###################################### Setting the Splash Screen ##########################################
  383. # ###########################################################################################################
  384. splash_settings = QSettings("Open Source", "FlatCAM")
  385. if splash_settings.contains("splash_screen"):
  386. show_splash = splash_settings.value("splash_screen")
  387. else:
  388. splash_settings.setValue('splash_screen', 1)
  389. # This will write the setting to the platform specific storage.
  390. del splash_settings
  391. show_splash = 1
  392. if show_splash and self.cmd_line_headless != 1:
  393. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  394. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  395. # self.splash.setMask(splash_pix.mask())
  396. # move splashscreen to the current monitor
  397. desktop = QtWidgets.QApplication.desktop()
  398. screen = desktop.screenNumber(QtGui.QCursor.pos())
  399. current_screen_center = desktop.availableGeometry(screen).center()
  400. self.splash.move(current_screen_center - self.splash.rect().center())
  401. self.splash.show()
  402. self.splash.showMessage(_("The application is initializing ..."),
  403. alignment=Qt.AlignBottom | Qt.AlignLeft,
  404. color=QtGui.QColor("gray"))
  405. else:
  406. self.splash = None
  407. show_splash = 0
  408. # ###########################################################################################################
  409. # ######################################### Initialize GUI ##################################################
  410. # ###########################################################################################################
  411. # FlatCAM colors used in plotting
  412. self.FC_light_green = '#BBF268BF'
  413. self.FC_dark_green = '#006E20BF'
  414. self.FC_light_blue = '#a5a5ffbf'
  415. self.FC_dark_blue = '#0000ffbf'
  416. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  417. if theme_settings.contains("theme"):
  418. theme = theme_settings.value('theme', type=str)
  419. else:
  420. theme = 'white'
  421. if self.defaults["global_cursor_color_enabled"]:
  422. self.cursor_color_3D = self.defaults["global_cursor_color"]
  423. else:
  424. if theme == 'white':
  425. self.cursor_color_3D = 'black'
  426. else:
  427. self.cursor_color_3D = 'gray'
  428. # update the defaults dict with the setting in QSetting
  429. self.defaults['global_theme'] = theme
  430. self.ui = MainGUI(self)
  431. # set FlatCAM units in the Status bar
  432. self.set_screen_units(self.defaults['units'])
  433. # ###########################################################################################################
  434. # ########################################### AUTOSAVE SETUP ################################################
  435. # ###########################################################################################################
  436. self.block_autosave = False
  437. self.autosave_timer = QtCore.QTimer(self)
  438. self.save_project_auto_update()
  439. self.autosave_timer.timeout.connect(self.save_project_auto)
  440. # ###########################################################################################################
  441. # #################################### LOAD PREPROCESSORS ###################################################
  442. # ###########################################################################################################
  443. # ----------------------------------------- WARNING --------------------------------------------------------
  444. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  445. # That's because the number of preprocessors can vary and here the comboboxes are populated
  446. # -----------------------------------------------------------------------------------------------------------
  447. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  448. # the preprocessor file
  449. self.preprocessors = load_preprocessors(self)
  450. # make sure that always the 'default' preprocessor is the first item in the dictionary
  451. if 'default' in self.preprocessors.keys():
  452. new_ppp_dict = {}
  453. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  454. default_pp = self.preprocessors.pop('default')
  455. new_ppp_dict['default'] = default_pp
  456. # then add the rest of the keys
  457. for name, val_class in self.preprocessors.items():
  458. new_ppp_dict[name] = val_class
  459. # and now put back the ordered dict with 'default' key first
  460. self.preprocessors = new_ppp_dict
  461. # populate the Preprocessor ComboBoxes in the PREFERENCES
  462. for name in list(self.preprocessors.keys()):
  463. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  464. if name.partition('_')[0] == 'Paste':
  465. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  466. continue
  467. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  468. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  469. if name == 'hpgl':
  470. continue
  471. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  472. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  473. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  474. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  475. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  476. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  477. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  478. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  479. QtCore.Qt.ToolTipRole)
  480. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  481. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  482. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  483. QtCore.Qt.ToolTipRole)
  484. # ###########################################################################################################
  485. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  486. # ###########################################################################################################
  487. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  488. inform=self.inform)
  489. self.preferencesUiManager.defaults_write_form()
  490. # When the self.defaults dictionary changes will update the Preferences GUI forms
  491. self.defaults.set_change_callback(self.on_defaults_dict_change)
  492. # ###########################################################################################################
  493. # ##################################### FIRST RUN SECTION ###################################################
  494. # ################################ It's done only once after install #####################################
  495. # ###########################################################################################################
  496. if self.defaults["first_run"] is True:
  497. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  498. initial_lay = 'minimal'
  499. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  500. # Set the combobox in Preferences to the current layout
  501. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  502. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  503. # after the first run, this object should be False
  504. self.defaults["first_run"] = False
  505. self.preferencesUiManager.save_defaults(silent=True)
  506. # ###########################################################################################################
  507. # ############################################ Data #########################################################
  508. # ###########################################################################################################
  509. self.recent = []
  510. self.recent_projects = []
  511. self.clipboard = QtWidgets.QApplication.clipboard()
  512. self.project_filename = None
  513. self.toggle_units_ignore = False
  514. self.main_thread = QtWidgets.QApplication.instance().thread()
  515. # ###########################################################################################################
  516. # ########################################## LOAD LANGUAGES ################################################
  517. # ###########################################################################################################
  518. self.languages = fcTranslate.load_languages()
  519. for name in sorted(self.languages.values()):
  520. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  521. # ###########################################################################################################
  522. # ####################################### APPLY APP LANGUAGE ################################################
  523. # ###########################################################################################################
  524. ret_val = fcTranslate.apply_language('strings')
  525. if ret_val == "no language":
  526. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  527. self.log.debug("Could not find the Language files. The App strings are missing.")
  528. else:
  529. # make the current language the current selection on the language combobox
  530. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  531. self.log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  532. # ###########################################################################################################
  533. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  534. # ###########################################################################################################
  535. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  536. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  537. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  538. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  539. self.defaults.propagate_defaults()
  540. # ###########################################################################################################
  541. # ######################################## UPDATE THE OPTIONS ###############################################
  542. # ###########################################################################################################
  543. self.options = LoudDict()
  544. # -----------------------------------------------------------------------------------------------------------
  545. # Update the self.options from the self.defaults
  546. # The self.defaults holds the application defaults while the self.options holds the object defaults
  547. # -----------------------------------------------------------------------------------------------------------
  548. # Copy app defaults to project options
  549. for def_key, def_val in self.defaults.items():
  550. self.options[def_key] = deepcopy(def_val)
  551. self.preferencesUiManager.show_preferences_gui()
  552. # ### End of Data ####
  553. # ###########################################################################################################
  554. # #################################### SETUP OBJECT COLLECTION ##############################################
  555. # ###########################################################################################################
  556. self.collection = ObjectCollection(app=self)
  557. self.ui.project_tab_layout.addWidget(self.collection.view)
  558. self.app_obj = AppObject(app=self)
  559. # ### Adjust tabs width ## ##
  560. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  561. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  562. self.collection.view.setMinimumWidth(290)
  563. self.log.debug("Finished creating Object Collection.")
  564. # ###########################################################################################################
  565. # ######################################## SETUP Plot Area ##################################################
  566. # ###########################################################################################################
  567. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  568. if self.defaults["global_graphic_engine"] == '3D':
  569. self.is_legacy = False
  570. else:
  571. self.is_legacy = True
  572. # Event signals disconnect id holders
  573. self.mp = None
  574. self.mm = None
  575. self.mr = None
  576. self.mdc = None
  577. self.mp_zc = None
  578. self.kp = None
  579. # Matplotlib axis
  580. self.axes = None
  581. if show_splash:
  582. self.splash.showMessage(_("The application is initializing ...\n"
  583. "Canvas initialization started."),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. start_plot_time = time.time() # debug
  587. self.plotcanvas = None
  588. self.app_cursor = None
  589. self.hover_shapes = None
  590. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  591. # setup the PlotCanvas
  592. self.on_plotcanvas_setup()
  593. end_plot_time = time.time()
  594. self.used_time = end_plot_time - start_plot_time
  595. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  596. if show_splash:
  597. self.splash.showMessage('%s: %ssec' % (_("The application is initializing ...\n"
  598. "Canvas initialization started.\n"
  599. "Canvas initialization finished in"), '%.2f' % self.used_time),
  600. alignment=Qt.AlignBottom | Qt.AlignLeft,
  601. color=QtGui.QColor("gray"))
  602. self.ui.splitter.setStretchFactor(1, 2)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ############################################
  614. # ###########################################################################################################
  615. # self.activity_view = FlatCAMActivityView(app=self)
  616. # self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  618. # ###########################################################################################################
  619. # ########################################## Other setups ###################################################
  620. # ###########################################################################################################
  621. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  622. # depending on from where those tools are called different actions can be done
  623. self.call_source = 'app'
  624. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  625. self.tool_tab_locked = False
  626. # decide if to show or hide the Notebook side of the screen at startup
  627. if self.defaults["global_project_at_startup"] is True:
  628. self.ui.splitter.setSizes([1, 1])
  629. else:
  630. self.ui.splitter.setSizes([0, 1])
  631. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  632. self.setup_default_properties_tab()
  633. # ###########################################################################################################
  634. # ####################################### Auto-complete KEYWORDS ############################################
  635. # ###########################################################################################################
  636. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  637. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  638. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  639. 'export_exc',
  640. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  641. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  642. 'interiors', 'isolate', 'join_excellon',
  643. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  644. 'mirror', 'ncc',
  645. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  646. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  647. 'options', 'origin',
  648. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  649. 'save', 'save_project',
  650. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  651. 'skew', 'subtract_poly', 'subtract_rectangle',
  652. 'version', 'write_gcode'
  653. ]
  654. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  655. 'Paste_1',
  656. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  657. 'Toolchange_manual', 'True', 'Users',
  658. 'all', 'auto', 'axis',
  659. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  660. 'contour', 'default',
  661. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  662. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  663. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  664. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  665. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  666. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  667. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  668. 'spacing_columns',
  669. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  670. 'toolchange_xy', 'toolchangez', 'travelz',
  671. 'tooldia', 'use_threads', 'value',
  672. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  673. ]
  674. self.tcl_keywords = [
  675. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  676. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  677. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  678. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  679. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  680. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  681. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  682. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  683. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  684. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  685. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  686. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  687. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  688. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  689. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  690. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  691. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  692. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  693. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  694. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  695. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  696. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  697. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  698. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  699. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  700. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  701. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  702. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  703. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  704. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  705. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  706. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  707. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  708. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  709. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  710. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  711. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  712. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  713. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  714. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  715. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  716. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  717. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  718. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  719. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  720. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  721. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  722. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  723. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  724. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  725. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  726. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  727. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  728. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  729. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  730. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  731. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  732. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  733. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  734. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  735. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  736. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  737. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  738. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  739. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  740. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  741. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  742. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  743. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  744. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  745. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  746. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  747. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  748. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  749. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  750. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  751. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  752. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  753. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  754. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  755. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  756. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  757. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  758. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  759. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  760. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  761. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  762. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  763. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  764. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  765. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  766. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  767. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  768. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  769. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  770. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  771. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  772. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  773. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  774. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  775. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  776. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  777. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  778. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  779. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  780. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  781. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  782. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  783. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  784. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  785. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  786. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  787. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  788. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  789. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  790. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  791. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  792. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  793. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  794. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  795. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  796. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  797. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  798. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  799. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  800. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  801. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  802. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  803. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  804. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  805. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  806. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  807. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  808. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  809. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  810. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  811. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  812. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  813. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  814. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  815. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  816. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  817. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  818. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  819. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  820. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  821. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  822. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  823. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  824. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  825. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  826. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  827. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  828. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  829. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  830. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  831. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  832. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  833. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  834. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  835. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  836. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  837. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  838. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  839. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  840. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  841. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  842. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  843. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  844. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  845. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  846. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  847. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  848. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  849. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  850. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  851. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  852. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  853. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  854. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  855. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  856. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  857. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  858. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  859. ]
  860. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  861. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  862. # ###########################################################################################################
  863. # ########################################## Tools and Plugins ##############################################
  864. # ###########################################################################################################
  865. self.shell = None
  866. self.dblsidedtool = None
  867. self.distance_tool = None
  868. self.distance_min_tool = None
  869. self.panelize_tool = None
  870. self.film_tool = None
  871. self.paste_tool = None
  872. self.calculator_tool = None
  873. self.rules_tool = None
  874. self.sub_tool = None
  875. self.move_tool = None
  876. self.cutout_tool = None
  877. self.ncclear_tool = None
  878. self.paint_tool = None
  879. self.isolation_tool = None
  880. self.drilling_tool = None
  881. self.optimal_tool = None
  882. self.transform_tool = None
  883. self.properties_tool = None
  884. self.pdf_tool = None
  885. self.image_tool = None
  886. self.pcb_wizard_tool = None
  887. self.cal_exc_tool = None
  888. self.qrcode_tool = None
  889. self.copper_thieving_tool = None
  890. self.fiducial_tool = None
  891. self.edrills_tool = None
  892. self.align_objects_tool = None
  893. self.punch_tool = None
  894. self.invert_tool = None
  895. self.corners_tool = None
  896. self.etch_tool = None
  897. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  898. try:
  899. self.install_tools()
  900. except AttributeError as e:
  901. self.log.debug("App.__init__() install_tools() --> %s" % str(e))
  902. # ###########################################################################################################
  903. # ######################################### BookMarks Manager ###############################################
  904. # ###########################################################################################################
  905. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  906. self.install_bookmarks()
  907. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  908. # ###########################################################################################################
  909. # ########################################### Tools Database ################################################
  910. # ###########################################################################################################
  911. self.tools_db_tab = None
  912. # ### System Font Parsing ###
  913. # self.f_parse = ParseFont(self)
  914. # self.parse_system_fonts()
  915. # ###########################################################################################################
  916. # ############################################## Shell SETUP ################################################
  917. # ###########################################################################################################
  918. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  919. if self.defaults["global_shell_at_startup"]:
  920. self.ui.shell_dock.show()
  921. else:
  922. self.ui.shell_dock.hide()
  923. # ###########################################################################################################
  924. # ######################################### Check for updates ###############################################
  925. # ###########################################################################################################
  926. # Separate thread (Not worker)
  927. # Check for updates on startup but only if the user consent and the app is not in Beta version
  928. if (self.beta is False or self.beta is None) and \
  929. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  930. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  931. # self.thr2 = QtCore.QThread()
  932. self.worker_task.emit({'fcn': self.version_check,
  933. 'params': []})
  934. # self.thr2.start(QtCore.QThread.LowPriority)
  935. # ###########################################################################################################
  936. # ##################################### Register files with FlatCAM; #######################################
  937. # ################################### It works only for Windows for now ####################################
  938. # ###########################################################################################################
  939. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  940. self.on_register_files()
  941. # ###########################################################################################################
  942. # ######################################## Variables for global usage #######################################
  943. # ###########################################################################################################
  944. # hold the App units
  945. self.units = 'MM'
  946. # coordinates for relative position display
  947. self.rel_point1 = (0, 0)
  948. self.rel_point2 = (0, 0)
  949. # variable to store coordinates
  950. self.pos = (0, 0)
  951. self.pos_canvas = (0, 0)
  952. self.pos_jump = (0, 0)
  953. # variable to store mouse coordinates
  954. self.mouse = [0, 0]
  955. # variable to store the delta positions on cavnas
  956. self.dx = 0
  957. self.dy = 0
  958. # decide if we have a double click or single click
  959. self.doubleclick = False
  960. # store here the is_dragging value
  961. self.event_is_dragging = False
  962. # variable to store if a command is active (then the var is not None) and which one it is
  963. self.command_active = None
  964. # variable to store the status of moving selection action
  965. # None value means that it's not an selection action
  966. # True value = a selection from left to right
  967. # False value = a selection from right to left
  968. self.selection_type = None
  969. # List to store the objects that are currently loaded in FlatCAM
  970. # This list is updated on each object creation or object delete
  971. self.all_objects_list = []
  972. self.objects_under_the_click_list = []
  973. # List to store the objects that are selected
  974. self.sel_objects_list = []
  975. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  976. self.key_modifiers = None
  977. # Variable to store the status of the code editor
  978. self.toggle_codeeditor = False
  979. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  980. self.click_noproject = False
  981. self.cursor = None
  982. # Variable to store the GCODE that was edited
  983. self.gcode_edited = ""
  984. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  985. self.old_state_of_tools_toolbar = False
  986. self.text_editor_tab = None
  987. # here store the color of a Tab text before it is changed so it can be restored in the future
  988. self.old_tab_text_color = None
  989. # reference for the self.ui.code_editor
  990. self.reference_code_editor = None
  991. self.script_code = ''
  992. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  993. self.tools_db_changed_flag = False
  994. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  995. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  996. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  997. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  998. 'tsm']
  999. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1000. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1001. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1002. 'sbp', 'tap', 'xpi']
  1003. self.svg_list = ['svg']
  1004. self.dxf_list = ['dxf']
  1005. self.pdf_list = ['pdf']
  1006. self.prj_list = ['flatprj']
  1007. self.conf_list = ['flatconfig']
  1008. # last used filters
  1009. self.last_op_gerber_filter = None
  1010. self.last_op_excellon_filter = None
  1011. self.last_op_gcode_filter = None
  1012. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1013. # flag for polygons not cleared
  1014. self.poly_not_cleared = False
  1015. # VisPy visuals
  1016. self.isHovering = False
  1017. self.notHovering = True
  1018. # Window geometry
  1019. self.x_pos = None
  1020. self.y_pos = None
  1021. self.width = None
  1022. self.height = None
  1023. # when True, the app has to return from any thread
  1024. self.abort_flag = False
  1025. # set the value used in the Windows Title
  1026. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1027. # this holds a widget that is installed in the Plot Area when View Source option is used
  1028. self.source_editor_tab = None
  1029. self.pagesize = {}
  1030. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1031. # VisPy visuals
  1032. if self.is_legacy is False:
  1033. try:
  1034. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1035. except AttributeError:
  1036. self.tool_shapes = None
  1037. else:
  1038. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1039. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1040. # used in the delayed shutdown self.start_delayed_quit() method
  1041. self.save_timer = None
  1042. # ###########################################################################################################
  1043. # ################################## ADDING FlatCAM EDITORS section #########################################
  1044. # ###########################################################################################################
  1045. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1046. # at the first launch of the App , the editors will not be functional.
  1047. try:
  1048. self.geo_editor = AppGeoEditor(self)
  1049. except Exception as es:
  1050. self.log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1051. try:
  1052. self.exc_editor = AppExcEditor(self)
  1053. except Exception as es:
  1054. self.log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1055. try:
  1056. self.grb_editor = AppGerberEditor(self)
  1057. except Exception as es:
  1058. self.log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1059. try:
  1060. self.gcode_editor = AppGCodeEditor(self)
  1061. except Exception as es:
  1062. self.log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1063. self.log.debug("Finished adding FlatCAM Editor's.")
  1064. self.ui.set_ui_title(name=_("New Project - Not saved"))
  1065. current_platform = platform.architecture()[0]
  1066. if current_platform != '64bit':
  1067. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1068. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1069. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1070. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1071. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1072. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1073. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1074. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1075. # ###########################################################################################################
  1076. # ########################################### EXCLUSION AREAS ###############################################
  1077. # ###########################################################################################################
  1078. self.exc_areas = ExclusionAreas(app=self)
  1079. # ###########################################################################################################
  1080. # ###########################################################################################################
  1081. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1082. # ###########################################################################################################
  1083. # ###########################################################################################################
  1084. self.f_handlers = MenuFileHandlers(app=self)
  1085. # this is calculated in the class above (somehow?)
  1086. self.defaults["root_folder_path"] = self.app_home
  1087. # ###########################################################################################################
  1088. # ############################################### SYS TRAY ##################################################
  1089. # ###########################################################################################################
  1090. if self.defaults["global_systray_icon"]:
  1091. self.parent_w = QtWidgets.QWidget()
  1092. if self.cmd_line_headless == 1:
  1093. self.trayIcon = FlatCAMSystemTray(app=self,
  1094. icon=QtGui.QIcon(self.resource_location +
  1095. '/flatcam_icon32_green.png'),
  1096. headless=True,
  1097. parent=self.parent_w)
  1098. else:
  1099. self.trayIcon = FlatCAMSystemTray(app=self,
  1100. icon=QtGui.QIcon(self.resource_location +
  1101. '/flatcam_icon32_green.png'),
  1102. parent=self.parent_w)
  1103. # ###########################################################################################################
  1104. # ############################################ SETUP RECENT ITEMS ###########################################
  1105. # ###########################################################################################################
  1106. self.setup_recent_items()
  1107. # ###########################################################################################################
  1108. # ###########################################################################################################
  1109. # ############################################# Signal handling #############################################
  1110. # ###########################################################################################################
  1111. # ###########################################################################################################
  1112. # ########################################## Custom signals ################################################
  1113. # signal for displaying messages in status bar
  1114. self.inform[str].connect(self.info)
  1115. self.inform[str, bool].connect(self.info)
  1116. # signal for displaying messages in the shell
  1117. self.inform_shell[str].connect(self.info_shell)
  1118. self.inform_shell[str, bool].connect(self.info_shell)
  1119. # signal to be called when the app is quiting
  1120. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1121. self.message.connect(lambda: message_dialog(parent=self.ui))
  1122. # self.progress.connect(self.set_progress_bar)
  1123. # signals emitted when file state change
  1124. self.file_opened.connect(self.register_recent)
  1125. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1126. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1127. # when the defaults dictionary values change
  1128. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1129. # ########################################## Standard signals ###############################################
  1130. # ### Menu
  1131. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1132. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1133. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1134. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1135. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1136. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1137. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1138. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1139. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1140. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1141. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1142. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1143. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1144. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1145. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1146. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1147. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1148. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1149. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1150. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1151. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1152. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1153. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1154. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1155. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1156. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1157. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1158. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1159. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1160. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1161. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1162. self.ui.menufile_exit.triggered.connect(self.final_save)
  1163. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1164. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1165. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1166. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1167. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1168. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1169. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1170. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1171. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1172. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1173. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1174. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1175. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1176. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1177. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1178. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1179. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1180. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1181. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1182. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1183. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1184. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1185. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1186. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1187. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1188. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1189. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1190. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1191. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1192. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1193. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1194. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1195. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1196. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1197. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1198. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1199. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1200. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1201. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1202. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1203. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1204. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1205. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1206. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1207. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1208. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1209. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1210. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1211. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1212. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1213. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1214. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1215. self.ui.menuhelp_readme.triggered.connect(self.on_howto)
  1216. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1217. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1218. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1219. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1220. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1221. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1222. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1223. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1224. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1225. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1226. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1227. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1228. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1229. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1230. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1231. # ToolBar signals
  1232. self.connect_toolbar_signals(ui=self.ui)
  1233. # Context Menu
  1234. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1235. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1236. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1237. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1238. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1239. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1240. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1241. self.ui.clearplot.triggered.connect(self.clear_plots)
  1242. self.ui.replot.triggered.connect(self.plot_all)
  1243. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1244. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1245. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1246. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1247. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1248. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1249. # Project Context Menu -> Color Setting
  1250. for act in self.ui.menuprojectcolor.actions():
  1251. act.triggered.connect(self.on_set_color_action_triggered)
  1252. # Notebook tab clicking
  1253. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1254. # ###########################################################################################################
  1255. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1256. # ###########################################################################################################
  1257. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1258. lambda: self.on_toggle_units(no_pref=False))
  1259. # ##################################### Workspace Setting Signals ###########################################
  1260. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1261. self.on_workspace_modified)
  1262. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1263. self.on_workspace_modified
  1264. )
  1265. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1266. # ###########################################################################################################
  1267. # ######################################## GUI SETTINGS SIGNALS #############################################
  1268. # ###########################################################################################################
  1269. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1270. # ######################################## Tools related signals ############################################
  1271. # portability changed signal
  1272. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1273. # Object list
  1274. self.object_status_changed.connect(self.collection.on_collection_updated)
  1275. # when there are arguments at application startup this get launched
  1276. self.args_at_startup[list].connect(self.on_startup_args)
  1277. # ###########################################################################################################
  1278. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1279. # ###########################################################################################################
  1280. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1281. lambda: self.restore_extensions(ext_type='excellon'))
  1282. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1283. lambda: self.restore_extensions(ext_type='gcode'))
  1284. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1285. lambda: self.restore_extensions(ext_type='gerber'))
  1286. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1287. lambda: self.delete_all_extensions(ext_type='excellon'))
  1288. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1289. lambda: self.delete_all_extensions(ext_type='gcode'))
  1290. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1291. lambda: self.delete_all_extensions(ext_type='gerber'))
  1292. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1293. lambda: self.add_extension(ext_type='excellon'))
  1294. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1295. lambda: self.add_extension(ext_type='gcode'))
  1296. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1297. lambda: self.add_extension(ext_type='gerber'))
  1298. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1299. lambda: self.del_extension(ext_type='excellon'))
  1300. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1301. lambda: self.del_extension(ext_type='gcode'))
  1302. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1303. lambda: self.del_extension(ext_type='gerber'))
  1304. # connect the 'Apply' buttons from the Preferences/File Associations
  1305. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1306. lambda: self.on_register_files(obj_type='excellon'))
  1307. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1308. lambda: self.on_register_files(obj_type='gcode'))
  1309. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1310. lambda: self.on_register_files(obj_type='gerber'))
  1311. # ###########################################################################################################
  1312. # ########################################### KEYWORDS SIGNALS ##############################################
  1313. # ###########################################################################################################
  1314. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1315. lambda: self.restore_extensions(ext_type='keyword'))
  1316. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1317. lambda: self.delete_all_extensions(ext_type='keyword'))
  1318. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1319. lambda: self.add_extension(ext_type='keyword'))
  1320. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1321. lambda: self.del_extension(ext_type='keyword'))
  1322. # ###########################################################################################################
  1323. # ########################################### GUI SIGNALS ###################################################
  1324. # ###########################################################################################################
  1325. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1326. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1327. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1328. # ###########################################################################################################
  1329. # ####################################### VARIOUS SIGNALS ###################################################
  1330. # ###########################################################################################################
  1331. # connect the abort_all_tasks related slots to the related signals
  1332. self.proc_container.idle_flag.connect(self.app_is_idle)
  1333. # signal emitted when a tab is closed in the Plot Area
  1334. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1335. # signal to close the application
  1336. self.close_app_signal.connect(self.kill_app)
  1337. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1338. # ###########################################################################################################
  1339. # ###########################################################################################################
  1340. # ###########################################################################################################
  1341. self.log.debug("Finished connecting Signals.")
  1342. # ###########################################################################################################
  1343. # ##################################### Finished the CONSTRUCTOR ############################################
  1344. # ###########################################################################################################
  1345. self.log.debug("END of constructor. Releasing control.")
  1346. # ###########################################################################################################
  1347. # ########################################## SHOW GUI #######################################################
  1348. # ###########################################################################################################
  1349. # if the app is not started as headless, show it
  1350. if self.cmd_line_headless != 1:
  1351. if show_splash:
  1352. # finish the splash
  1353. self.splash.finish(self.ui)
  1354. mgui_settings = QSettings("Open Source", "FlatCAM")
  1355. if mgui_settings.contains("maximized_gui"):
  1356. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1357. if maximized_ui is True:
  1358. self.ui.showMaximized()
  1359. else:
  1360. self.ui.show()
  1361. else:
  1362. self.ui.show()
  1363. if self.defaults["global_systray_icon"]:
  1364. self.trayIcon.show()
  1365. else:
  1366. log.warning("******************* RUNNING HEADLESS *******************")
  1367. # ###########################################################################################################
  1368. # ######################################## START-UP ARGUMENTS ###############################################
  1369. # ###########################################################################################################
  1370. # test if the program was started with a script as parameter
  1371. if self.cmd_line_shellvar:
  1372. try:
  1373. cnt = 0
  1374. command_tcl = 0
  1375. for i in self.cmd_line_shellvar.split(','):
  1376. if i is not None:
  1377. # noinspection PyBroadException
  1378. try:
  1379. command_tcl = eval(i)
  1380. except Exception:
  1381. command_tcl = i
  1382. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1383. cnt += 1
  1384. # if there are Windows paths then replace the path separator with a Unix like one
  1385. if sys.platform == 'win32':
  1386. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1387. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1388. except Exception as ext:
  1389. print("ERROR: ", ext)
  1390. sys.exit(2)
  1391. if self.cmd_line_shellfile:
  1392. if self.cmd_line_headless != 1:
  1393. if self.ui.shell_dock.isHidden():
  1394. self.ui.shell_dock.show()
  1395. try:
  1396. with open(self.cmd_line_shellfile, "r") as myfile:
  1397. # if show_splash:
  1398. # self.splash.showMessage('%s: %ssec\n%s' % (
  1399. # _("Canvas initialization started.\n"
  1400. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1401. # _("Executing Tcl Script ...")),
  1402. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1403. # color=QtGui.QColor("gray"))
  1404. cmd_line_shellfile_text = myfile.read()
  1405. if self.cmd_line_headless != 1:
  1406. self.shell.exec_command(cmd_line_shellfile_text)
  1407. else:
  1408. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1409. except Exception as ext:
  1410. print("ERROR: ", ext)
  1411. sys.exit(2)
  1412. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1413. # the path/file_name must be enclosed in quotes if it contain spaces
  1414. if App.args:
  1415. self.args_at_startup.emit(App.args)
  1416. if self.defaults.old_defaults_found is True:
  1417. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1418. "Please reboot the application to update."))
  1419. self.defaults.old_defaults_found = False
  1420. # ######################################### INIT FINISHED #######################################################
  1421. # #################################################################################################################
  1422. # #################################################################################################################
  1423. # #################################################################################################################
  1424. # #################################################################################################################
  1425. # #################################################################################################################
  1426. @staticmethod
  1427. def copy_and_overwrite(from_path, to_path):
  1428. """
  1429. From here:
  1430. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1431. :param from_path: source path
  1432. :param to_path: destination path
  1433. :return: None
  1434. """
  1435. if os.path.exists(to_path):
  1436. shutil.rmtree(to_path)
  1437. try:
  1438. shutil.copytree(from_path, to_path)
  1439. except FileNotFoundError:
  1440. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1441. shutil.copytree(from_new_path, to_path)
  1442. def on_startup_args(self, args, silent=False):
  1443. """
  1444. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1445. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1446. :param args: a list containing the application args at startup
  1447. :return: None
  1448. """
  1449. if args is not None:
  1450. args_to_process = args
  1451. else:
  1452. args_to_process = App.args
  1453. self.log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1454. for argument in args_to_process:
  1455. if '.FlatPrj'.lower() in argument.lower():
  1456. try:
  1457. project_name = str(argument)
  1458. if project_name == "":
  1459. if silent is False:
  1460. self.inform.emit(_("Cancelled."))
  1461. else:
  1462. # self.open_project(project_name)
  1463. run_from_arg = True
  1464. # self.worker_task.emit({'fcn': self.open_project,
  1465. # 'params': [project_name, run_from_arg]})
  1466. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1467. except Exception as e:
  1468. self.log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1469. elif '.FlatConfig'.lower() in argument.lower():
  1470. try:
  1471. file_name = str(argument)
  1472. if file_name == "":
  1473. if silent is False:
  1474. self.inform.emit(_("Open Config file failed."))
  1475. else:
  1476. run_from_arg = True
  1477. # self.worker_task.emit({'fcn': self.open_config_file,
  1478. # 'params': [file_name, run_from_arg]})
  1479. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1480. except Exception as e:
  1481. self.log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1482. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1483. try:
  1484. file_name = str(argument)
  1485. if file_name == "":
  1486. if silent is False:
  1487. self.inform.emit(_("Open Script file failed."))
  1488. else:
  1489. if silent is False:
  1490. self.on_fileopenscript(name=file_name)
  1491. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1492. self.on_filerunscript(name=file_name)
  1493. except Exception as e:
  1494. self.log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1495. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1496. self.log.debug("App.on_startup_args() --> Quit event.")
  1497. sys.exit()
  1498. elif 'save'.lower() in argument.lower():
  1499. self.log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1500. self.preferencesUiManager.save_defaults()
  1501. else:
  1502. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1503. proc_arg = argument.lower()
  1504. for ext in exc_list:
  1505. proc_ext = ext.replace(' ', '')
  1506. proc_ext = '.%s' % proc_ext
  1507. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1508. file_name = str(argument)
  1509. if file_name == "":
  1510. if silent is False:
  1511. self.inform.emit(_("Open Excellon file failed."))
  1512. else:
  1513. self.on_fileopenexcellon(name=file_name, signal=None)
  1514. return
  1515. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1516. for ext in gco_list:
  1517. proc_ext = ext.replace(' ', '')
  1518. proc_ext = '.%s' % proc_ext
  1519. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1520. file_name = str(argument)
  1521. if file_name == "":
  1522. if silent is False:
  1523. self.inform.emit(_("Open GCode file failed."))
  1524. else:
  1525. self.on_fileopengcode(name=file_name, signal=None)
  1526. return
  1527. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1528. for ext in grb_list:
  1529. proc_ext = ext.replace(' ', '')
  1530. proc_ext = '.%s' % proc_ext
  1531. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1532. file_name = str(argument)
  1533. if file_name == "":
  1534. if silent is False:
  1535. self.inform.emit(_("Open Gerber file failed."))
  1536. else:
  1537. self.on_fileopengerber(name=file_name, signal=None)
  1538. return
  1539. # if it reached here without already returning then the app was registered with a file that it does not
  1540. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1541. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1542. # for arg in args_to_process:
  1543. # if 'FlatCAM.exe' in arg:
  1544. # continue
  1545. # else:
  1546. # sys.exit(2)
  1547. def tools_database_path(self):
  1548. return os.path.join(self.data_path, 'tools_db.FlatDB')
  1549. def defaults_path(self):
  1550. return os.path.join(self.data_path, 'current_defaults.FlatConfig')
  1551. def factory_defaults_path(self):
  1552. return os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  1553. def recent_files_path(self):
  1554. return os.path.join(self.data_path, 'recent.json')
  1555. def recent_projects_path(self):
  1556. return os.path.join(self.data_path, 'recent_projects.json')
  1557. def preprocessors_path(self):
  1558. return os.path.join(self.data_path, 'preprocessors')
  1559. def on_app_restart(self):
  1560. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1561. # be left in the SySTray
  1562. try:
  1563. self.trayIcon.hide()
  1564. except Exception:
  1565. pass
  1566. fcTranslate.restart_program(app=self)
  1567. def clear_pool(self):
  1568. """
  1569. Clear the multiprocessing pool and calls garbage collector.
  1570. :return: None
  1571. """
  1572. self.pool.close()
  1573. self.pool = Pool()
  1574. self.pool_recreated.emit(self.pool)
  1575. gc.collect()
  1576. def install_tools(self):
  1577. """
  1578. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1579. Instantiation of the Tools classes.
  1580. The order that the tools are installed is important as they can depend on each other install position.
  1581. :return: None
  1582. """
  1583. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1584. self.shell = FCShell(app=self, version=self.version)
  1585. self.distance_tool = Distance(self)
  1586. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1587. before=self.ui.menueditorigin,
  1588. separator=False)
  1589. self.distance_min_tool = DistanceMin(self)
  1590. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1591. pos=self.ui.menuedit,
  1592. before=self.ui.menueditorigin,
  1593. separator=True)
  1594. self.dblsidedtool = DblSidedTool(self)
  1595. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1596. self.cal_exc_tool = ToolCalibration(self)
  1597. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1598. before=self.dblsidedtool.menuAction,
  1599. separator=False)
  1600. self.align_objects_tool = AlignObjects(self)
  1601. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1602. self.edrills_tool = ToolExtractDrills(self)
  1603. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1604. self.panelize_tool = Panelize(self)
  1605. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1606. self.film_tool = Film(self)
  1607. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1608. self.paste_tool = SolderPaste(self)
  1609. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1610. self.calculator_tool = ToolCalculator(self)
  1611. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1612. self.sub_tool = ToolSub(self)
  1613. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1614. pos=self.ui.menutool, separator=True)
  1615. self.rules_tool = RulesCheck(self)
  1616. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1617. pos=self.ui.menutool, separator=False)
  1618. self.optimal_tool = ToolOptimal(self)
  1619. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1620. pos=self.ui.menutool, separator=True)
  1621. self.move_tool = ToolMove(self)
  1622. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1623. before=self.ui.menueditorigin, separator=True)
  1624. self.cutout_tool = CutOut(self)
  1625. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1626. before=self.sub_tool.menuAction)
  1627. self.ncclear_tool = NonCopperClear(self)
  1628. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1629. before=self.sub_tool.menuAction, separator=True)
  1630. self.paint_tool = ToolPaint(self)
  1631. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1632. before=self.sub_tool.menuAction, separator=True)
  1633. self.isolation_tool = ToolIsolation(self)
  1634. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1635. before=self.sub_tool.menuAction, separator=True)
  1636. self.drilling_tool = ToolDrilling(self)
  1637. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1638. before=self.sub_tool.menuAction, separator=True)
  1639. self.copper_thieving_tool = ToolCopperThieving(self)
  1640. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1641. pos=self.ui.menutool)
  1642. self.fiducial_tool = ToolFiducials(self)
  1643. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1644. pos=self.ui.menutool)
  1645. self.qrcode_tool = QRCode(self)
  1646. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1647. pos=self.ui.menutool)
  1648. self.punch_tool = ToolPunchGerber(self)
  1649. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1650. self.invert_tool = ToolInvertGerber(self)
  1651. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1652. self.corners_tool = ToolCorners(self)
  1653. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1654. self.etch_tool = ToolEtchCompensation(self)
  1655. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1656. self.transform_tool = ToolTransform(self)
  1657. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1658. pos=self.ui.menuoptions, separator=True)
  1659. self.properties_tool = Properties(self)
  1660. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1661. pos=self.ui.menuoptions)
  1662. self.pdf_tool = ToolPDF(self)
  1663. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1664. pos=self.ui.menufileimport,
  1665. separator=True)
  1666. self.image_tool = ToolImage(self)
  1667. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1668. pos=self.ui.menufileimport,
  1669. separator=True)
  1670. self.pcb_wizard_tool = PcbWizard(self)
  1671. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1672. pos=self.ui.menufileimport)
  1673. self.log.debug("Tools are installed.")
  1674. def remove_tools(self):
  1675. """
  1676. Will remove all the actions in the Tool menu.
  1677. :return: None
  1678. """
  1679. for act in self.ui.menutool.actions():
  1680. self.ui.menutool.removeAction(act)
  1681. def init_tools(self):
  1682. """
  1683. Initialize the Tool tab in the notebook side of the central widget.
  1684. Remove the actions in the Tools menu.
  1685. Instantiate again the FlatCAM tools (plugins).
  1686. All this is required when changing the layout: standard, compact etc.
  1687. :return: None
  1688. """
  1689. self.log.debug("init_tools()")
  1690. # delete the data currently in the Tools Tab and the Tab itself
  1691. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1692. if widget is not None:
  1693. widget.deleteLater()
  1694. self.ui.notebook.removeTab(2)
  1695. # rebuild the Tools Tab
  1696. self.ui.tool_tab = QtWidgets.QWidget()
  1697. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1698. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1699. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1700. self.ui.tool_scroll_area = VerticalScrollArea()
  1701. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1702. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1703. # first remove all of them
  1704. self.remove_tools()
  1705. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1706. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1707. '&Command Line\tS')
  1708. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1709. # third install all of them
  1710. try:
  1711. self.install_tools()
  1712. except AttributeError:
  1713. pass
  1714. self.log.debug("Tools are initialized.")
  1715. # def parse_system_fonts(self):
  1716. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1717. # 'params': []})
  1718. def connect_tools_signals_to_toolbar(self, ui):
  1719. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1720. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1721. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1722. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1723. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1724. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1725. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1726. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1727. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1728. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1729. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1730. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1731. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1732. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1733. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1734. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1735. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1736. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1737. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1738. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1739. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1740. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1741. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1742. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1743. def connect_toolbar_signals(self, ui):
  1744. """
  1745. Reconnect the signals to the actions in the toolbar.
  1746. This has to be done each time after the FlatCAM tools are removed/installed.
  1747. :return: None
  1748. """
  1749. # Toolbar
  1750. # File Toolbar Signals
  1751. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1752. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1753. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1754. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1755. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1756. # View Toolbar Signals
  1757. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1758. ui.replot_btn.triggered.connect(self.plot_all)
  1759. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1760. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1761. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1762. # Edit Toolbar Signals
  1763. ui.editgeo_btn.triggered.connect(self.object2editor)
  1764. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1765. ui.copy_btn.triggered.connect(self.on_copy_command)
  1766. ui.delete_btn.triggered.connect(self.on_delete)
  1767. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1768. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1769. ui.origin_btn.triggered.connect(self.on_set_origin)
  1770. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1771. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1772. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1773. # Scripting Toolbar Signals
  1774. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1775. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1776. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1777. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1778. # Tools Toolbar Signals
  1779. try:
  1780. self.connect_tools_signals_to_toolbar(ui=ui)
  1781. except Exception as err:
  1782. self.log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1783. def object2editor(self):
  1784. """
  1785. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1786. :return: None
  1787. """
  1788. self.defaults.report_usage("object2editor()")
  1789. self.log.debug("######################### Starting the EDITOR ################################")
  1790. # disable the objects menu as it may interfere with the appEditors
  1791. self.ui.menuobjects.setDisabled(True)
  1792. edited_object = self.collection.get_active()
  1793. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1794. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1795. pass
  1796. else:
  1797. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1798. return
  1799. if isinstance(edited_object, GeometryObject):
  1800. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1801. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1802. # we set the notebook to hidden
  1803. # self.ui.splitter.setSizes([0, 1])
  1804. if edited_object.multigeo is True:
  1805. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1806. if len(sel_rows) > 1:
  1807. self.inform.emit('[WARNING_NOTCL] %s' %
  1808. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1809. "is not possible.\n"
  1810. "Edit only one geometry at a time."))
  1811. if not sel_rows:
  1812. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1813. return
  1814. # determine the tool dia of the selected tool
  1815. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1816. # now find the key in the edited_object.tools that has this tooldia
  1817. multi_tool = 1
  1818. for tool in edited_object.tools:
  1819. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1820. multi_tool = tool
  1821. break
  1822. self.log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1823. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1824. else:
  1825. self.log.debug("Editing SingleGeo Geometry with tool diameter.")
  1826. self.geo_editor.edit_fcgeometry(edited_object)
  1827. # set call source to the Editor we go into
  1828. self.call_source = 'geo_editor'
  1829. elif isinstance(edited_object, ExcellonObject):
  1830. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1831. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1832. if self.ui.splitter.sizes()[0] == 0:
  1833. self.ui.splitter.setSizes([1, 1])
  1834. self.exc_editor.edit_fcexcellon(edited_object)
  1835. # set call source to the Editor we go into
  1836. self.call_source = 'exc_editor'
  1837. elif isinstance(edited_object, GerberObject):
  1838. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1839. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1840. if self.ui.splitter.sizes()[0] == 0:
  1841. self.ui.splitter.setSizes([1, 1])
  1842. self.grb_editor.edit_fcgerber(edited_object)
  1843. # set call source to the Editor we go into
  1844. self.call_source = 'grb_editor'
  1845. # reset the following variables so the UI is built again after edit
  1846. edited_object.ui_build = False
  1847. elif isinstance(edited_object, CNCJobObject):
  1848. if self.ui.splitter.sizes()[0] == 0:
  1849. self.ui.splitter.setSizes([1, 1])
  1850. # set call source to the Editor we go into
  1851. self.call_source = 'gcode_editor'
  1852. self.gcode_editor.edit_fcgcode(edited_object)
  1853. # make sure that we can't select another object while in Editor Mode:
  1854. self.ui.project_frame.setDisabled(True)
  1855. for idx in range(self.ui.notebook.count()):
  1856. # store the Properties Tab text color here and change the color and text
  1857. if self.ui.notebook.tabText(idx) == _("Properties"):
  1858. self.old_tab_text_color = self.ui.notebook.tabBar.tabTextColor(idx)
  1859. self.ui.notebook.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  1860. self.ui.notebook.tabBar.setTabText(idx, _("Editor"))
  1861. # disable the Project Tab
  1862. if self.ui.notebook.tabText(idx) == _("Project"):
  1863. self.ui.notebook.tabBar.setTabEnabled(idx, False)
  1864. # delete any selection shape that might be active as they are not relevant in Editor
  1865. self.delete_selection_shape()
  1866. # hide the Tools Toolbar
  1867. tools_tb = self.ui.toolbartools
  1868. if tools_tb.isVisible():
  1869. self.old_state_of_tools_toolbar = True
  1870. tools_tb.hide()
  1871. else:
  1872. self.old_state_of_tools_toolbar = False
  1873. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1874. self.ui.plot_tab_area.protectTab(0)
  1875. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1876. self.should_we_save = True
  1877. def editor2object(self, cleanup=None):
  1878. """
  1879. Transfers the Geometry or Excellon from it's editor to the current object.
  1880. :return: None
  1881. """
  1882. self.defaults.report_usage("editor2object()")
  1883. self.log.debug("######################### Closing the EDITOR ################################")
  1884. # re-enable the objects menu that was disabled on entry in Editor mode
  1885. self.ui.menuobjects.setDisabled(False)
  1886. # do not update a geometry or excellon object unless it comes out of an editor
  1887. if self.call_source != 'app':
  1888. edited_obj = self.collection.get_active()
  1889. if cleanup is None:
  1890. msgbox = QtWidgets.QMessageBox()
  1891. msgbox.setText(_("Do you want to save the edited object?"))
  1892. msgbox.setWindowTitle(_("Close Editor"))
  1893. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1894. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1895. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1896. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1897. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1898. msgbox.setDefaultButton(bt_yes)
  1899. msgbox.exec_()
  1900. response = msgbox.clickedButton()
  1901. if response == bt_yes:
  1902. # show the Tools Toolbar
  1903. tools_tb = self.ui.toolbartools
  1904. if self.old_state_of_tools_toolbar is True:
  1905. tools_tb.show()
  1906. # clean the Tools Tab
  1907. self.ui.tool_scroll_area.takeWidget()
  1908. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1909. self.ui.notebook.setTabText(2, _("Tool"))
  1910. if edited_obj.kind == 'geometry':
  1911. obj_type = "Geometry"
  1912. self.geo_editor.update_fcgeometry(edited_obj)
  1913. # self.geo_editor.update_options(edited_obj)
  1914. # restore GUI to the Selected TAB
  1915. # Remove anything else in the appGUI
  1916. self.ui.tool_scroll_area.takeWidget()
  1917. # update the geo object options so it is including the bounding box values
  1918. try:
  1919. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1920. edited_obj.options['xmin'] = xmin
  1921. edited_obj.options['ymin'] = ymin
  1922. edited_obj.options['xmax'] = xmax
  1923. edited_obj.options['ymax'] = ymax
  1924. except AttributeError as e:
  1925. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1926. self.log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1927. edited_obj.build_ui()
  1928. edited_obj.plot()
  1929. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1930. elif edited_obj.kind == 'gerber':
  1931. obj_type = "Gerber"
  1932. self.grb_editor.update_fcgerber()
  1933. # self.grb_editor.update_options(edited_obj)
  1934. # delete the old object (the source object) if it was an empty one
  1935. try:
  1936. if len(edited_obj.solid_geometry) == 0:
  1937. old_name = edited_obj.options['name']
  1938. self.collection.delete_by_name(old_name)
  1939. except TypeError:
  1940. # if the solid_geometry is a single Polygon the len() will not work
  1941. # in any case, falling here means that we have something in the solid_geometry, even if only
  1942. # a single Polygon, therefore we pass this
  1943. pass
  1944. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1945. # restore GUI to the Selected TAB
  1946. # Remove anything else in the GUI
  1947. self.ui.properties_scroll_area.takeWidget()
  1948. elif edited_obj.kind == 'excellon':
  1949. obj_type = "Excellon"
  1950. self.exc_editor.update_fcexcellon(edited_obj)
  1951. # self.exc_editor.update_options(edited_obj)
  1952. # restore GUI to the Selected TAB
  1953. # Remove anything else in the GUI
  1954. self.ui.tool_scroll_area.takeWidget()
  1955. # delete the old object (the source object) if it was an empty one
  1956. # find if we have drills:
  1957. has_drills = None
  1958. for tt in edited_obj.tools:
  1959. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1960. has_drills = True
  1961. break
  1962. # find if we have slots:
  1963. has_slots = None
  1964. for tt in edited_obj.tools:
  1965. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1966. has_slots = True
  1967. break
  1968. if has_drills is None and has_slots is None:
  1969. old_name = edited_obj.options['name']
  1970. self.collection.delete_by_name(name=old_name)
  1971. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1972. elif edited_obj.kind == 'cncjob':
  1973. obj_type = "CNCJob"
  1974. self.gcode_editor.update_fcgcode(edited_obj)
  1975. # self.exc_editor.update_options(edited_obj)
  1976. # restore GUI to the Selected TAB
  1977. # Remove anything else in the GUI
  1978. self.ui.tool_scroll_area.takeWidget()
  1979. edited_obj.build_ui()
  1980. # close the open tab
  1981. for idx in range(self.ui.plot_tab_area.count()):
  1982. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1983. self.ui.plot_tab_area.closeTab(idx)
  1984. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1985. else:
  1986. self.inform.emit('[WARNING_NOTCL] %s' %
  1987. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1988. return
  1989. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1990. elif response == bt_no:
  1991. # show the Tools Toolbar
  1992. tools_tb = self.ui.toolbartools
  1993. if self.old_state_of_tools_toolbar is True:
  1994. tools_tb.show()
  1995. # clean the Tools Tab
  1996. self.ui.tool_scroll_area.takeWidget()
  1997. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1998. self.ui.notebook.setTabText(2, _("Tool"))
  1999. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2000. if edited_obj.kind == 'geometry':
  2001. self.geo_editor.deactivate()
  2002. edited_obj.build_ui()
  2003. edited_obj.plot()
  2004. elif edited_obj.kind == 'gerber':
  2005. self.grb_editor.deactivate_grb_editor()
  2006. edited_obj.build_ui()
  2007. elif edited_obj.kind == 'excellon':
  2008. self.exc_editor.deactivate()
  2009. edited_obj.build_ui()
  2010. elif edited_obj.kind == 'cncjob':
  2011. self.gcode_editor.deactivate()
  2012. edited_obj.build_ui()
  2013. # close the open tab
  2014. for idx in range(self.ui.plot_tab_area.count()):
  2015. try:
  2016. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2017. self.ui.plot_tab_area.closeTab(idx)
  2018. except AttributeError:
  2019. continue
  2020. else:
  2021. self.inform.emit('[WARNING_NOTCL] %s' %
  2022. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2023. return
  2024. elif response == bt_cancel:
  2025. return
  2026. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2027. # edited_obj.build_ui()
  2028. # Switch notebook to Properties page
  2029. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2030. else:
  2031. # show the Tools Toolbar
  2032. tools_tb = self.ui.toolbartools
  2033. if self.old_state_of_tools_toolbar is True:
  2034. tools_tb.show()
  2035. if isinstance(edited_obj, GeometryObject):
  2036. self.geo_editor.deactivate()
  2037. elif isinstance(edited_obj, GerberObject):
  2038. self.grb_editor.deactivate_grb_editor()
  2039. elif isinstance(edited_obj, ExcellonObject):
  2040. self.exc_editor.deactivate()
  2041. else:
  2042. self.inform.emit('[WARNING_NOTCL] %s' %
  2043. _("Select a Gerber, Geometry or Excellon Object to update."))
  2044. return
  2045. # if notebook is hidden we show it
  2046. if self.ui.splitter.sizes()[0] == 0:
  2047. self.ui.splitter.setSizes([1, 1])
  2048. for idx in range(self.ui.notebook.count()):
  2049. # restore the Properties Tab text and color
  2050. if self.ui.notebook.tabText(idx) == _("Editor"):
  2051. self.ui.notebook.tabBar.setTabTextColor(idx, self.old_tab_text_color)
  2052. self.ui.notebook.tabBar.setTabText(idx, _("Properties"))
  2053. # enable the Project Tab
  2054. if self.ui.notebook.tabText(idx) == _("Project"):
  2055. self.ui.notebook.tabBar.setTabEnabled(idx, True)
  2056. # restore the call_source to app
  2057. self.call_source = 'app'
  2058. # edited_obj.plot()
  2059. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2060. self.ui.plot_tab_area.protectTab(0)
  2061. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2062. self.ui.project_frame.setDisabled(False)
  2063. def get_last_folder(self):
  2064. """
  2065. Get the folder path from where the last file was opened.
  2066. :return: String, last opened folder path
  2067. """
  2068. return self.defaults["global_last_folder"]
  2069. def get_last_save_folder(self):
  2070. """
  2071. Get the folder path from where the last file was saved.
  2072. :return: String, last saved folder path
  2073. """
  2074. loc = self.defaults["global_last_save_folder"]
  2075. if loc is None:
  2076. loc = self.defaults["global_last_folder"]
  2077. if loc is None:
  2078. loc = os.path.dirname(__file__)
  2079. return loc
  2080. @QtCore.pyqtSlot(str)
  2081. @QtCore.pyqtSlot(str, bool)
  2082. def info(self, msg, shell_echo=True):
  2083. """
  2084. Informs the user. Normally on the status bar, optionally
  2085. also on the shell.
  2086. :param msg: Text to write.
  2087. :type msg: str
  2088. :param shell_echo: Control if to display the message msg in the Shell
  2089. :type shell_echo: bool
  2090. :return: None
  2091. """
  2092. # Type of message in brackets at the beginning of the message.
  2093. match = re.search(r"\[(.*)\](.*)", msg)
  2094. if match:
  2095. level = match.group(1)
  2096. msg_ = match.group(2)
  2097. self.ui.fcinfo.set_status(str(msg_), level=level)
  2098. if shell_echo is True:
  2099. if level.lower() == "error":
  2100. self.shell_message(msg, error=True, show=True)
  2101. elif level.lower() == "warning":
  2102. self.shell_message(msg, warning=True, show=True)
  2103. elif level.lower() == "error_notcl":
  2104. self.shell_message(msg, error=True, show=False)
  2105. elif level.lower() == "warning_notcl":
  2106. self.shell_message(msg, warning=True, show=False)
  2107. elif level.lower() == "success":
  2108. self.shell_message(msg, success=True, show=False)
  2109. elif level.lower() == "selected":
  2110. self.shell_message(msg, selected=True, show=False)
  2111. else:
  2112. self.shell_message(msg, show=False)
  2113. else:
  2114. self.ui.fcinfo.set_status(str(msg), level="info")
  2115. # make sure that if the message is to clear the infobar with a space
  2116. # is not printed over and over on the shell
  2117. if msg != '' and shell_echo is True:
  2118. self.shell_message(msg)
  2119. def info_shell(self, msg, new_line=True):
  2120. self.shell_message(msg=msg, new_line=new_line)
  2121. def save_to_file(self, content_to_save, txt_content):
  2122. """
  2123. Save something to a file.
  2124. :return: None
  2125. """
  2126. self.defaults.report_usage("save_to_file")
  2127. self.log.debug("save_to_file()")
  2128. self.date = str(datetime.today()).rpartition('.')[0]
  2129. self.date = ''.join(c for c in self.date if c not in ':-')
  2130. self.date = self.date.replace(' ', '_')
  2131. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2132. path_to_save = self.defaults["global_last_save_folder"] if \
  2133. self.defaults["global_last_save_folder"] is not None else self.data_path
  2134. try:
  2135. filename, _f = FCFileSaveDialog.get_saved_filename(
  2136. caption=_("Save to file"),
  2137. directory=path_to_save + '/file_' + self.date,
  2138. ext_filter=filter__
  2139. )
  2140. except TypeError:
  2141. filename, _f = FCFileSaveDialog.get_saved_filename(
  2142. caption=_("Save to file"),
  2143. ext_filter=filter__)
  2144. filename = str(filename)
  2145. if filename == "":
  2146. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2147. return
  2148. else:
  2149. try:
  2150. with open(filename, 'w') as f:
  2151. ___ = f.read()
  2152. except PermissionError:
  2153. self.inform.emit('[WARNING] %s' %
  2154. _("Permission denied, saving not possible.\n"
  2155. "Most likely another app is holding the file open and not accessible."))
  2156. return
  2157. except IOError:
  2158. self.log.debug('Creating a new file ...')
  2159. f = open(filename, 'w')
  2160. f.close()
  2161. except Exception:
  2162. e = sys.exc_info()[0]
  2163. App.log.error("Could not load the file.")
  2164. App.log.error(str(e))
  2165. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2166. return
  2167. # Save content
  2168. if filename.rpartition('.')[2].lower() == 'html':
  2169. file_content = content_to_save
  2170. else:
  2171. file_content = txt_content
  2172. try:
  2173. with open(filename, "w") as f:
  2174. f.write(file_content)
  2175. except Exception:
  2176. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2177. return
  2178. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2179. def register_recent(self, kind, filename):
  2180. """
  2181. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2182. dictionary.
  2183. :param kind: type of file that was opened
  2184. :param filename: the path and file name for the file that was opened
  2185. :return:
  2186. """
  2187. self.log.debug("register_recent()")
  2188. self.log.debug(" %s" % kind)
  2189. self.log.debug(" %s" % filename)
  2190. record = {'kind': str(kind), 'filename': str(filename)}
  2191. if record in self.recent:
  2192. return
  2193. if record in self.recent_projects:
  2194. return
  2195. if record['kind'] == 'project':
  2196. self.recent_projects.insert(0, record)
  2197. else:
  2198. self.recent.insert(0, record)
  2199. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2200. self.recent.pop()
  2201. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2202. self.recent_projects.pop()
  2203. try:
  2204. f = open(self.data_path + '/recent.json', 'w')
  2205. except IOError:
  2206. App.log.error("Failed to open recent items file for writing.")
  2207. self.inform.emit('[ERROR_NOTCL] %s' %
  2208. _('Failed to open recent files file for writing.'))
  2209. return
  2210. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2211. f.close()
  2212. try:
  2213. fp = open(self.data_path + '/recent_projects.json', 'w')
  2214. except IOError:
  2215. App.log.error("Failed to open recent items file for writing.")
  2216. self.inform.emit('[ERROR_NOTCL] %s' %
  2217. _('Failed to open recent projects file for writing.'))
  2218. return
  2219. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2220. fp.close()
  2221. # Re-build the recent items menu
  2222. self.setup_recent_items()
  2223. def on_about(self):
  2224. """
  2225. Displays the "about" dialog found in the Menu --> Help.
  2226. :return: None
  2227. """
  2228. self.defaults.report_usage("on_about")
  2229. version = self.version
  2230. version_date = self.version_date
  2231. beta = self.beta
  2232. class AboutDialog(QtWidgets.QDialog):
  2233. def __init__(self, app, parent=None):
  2234. QtWidgets.QDialog.__init__(self, parent)
  2235. self.app = app
  2236. # Icon and title
  2237. self.setWindowIcon(parent.app_icon)
  2238. self.setWindowTitle(_("About"))
  2239. self.resize(600, 200)
  2240. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2241. # self.setStyleSheet(
  2242. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2243. # "background-attachment: fixed"
  2244. # )
  2245. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2246. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2247. # palette = QtGui.QPalette()
  2248. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2249. # self.setPalette(palette)
  2250. logo = QtWidgets.QLabel()
  2251. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2252. title = QtWidgets.QLabel(
  2253. "<font size=8><B>FlatCAM</B></font><BR>"
  2254. "{title}<BR>"
  2255. "<BR>"
  2256. "<BR>"
  2257. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2258. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2259. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2260. "<B>{issue}</B></a><BR>".format(
  2261. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2262. devel=_("Development"),
  2263. down=_("DOWNLOAD"),
  2264. issue=_("Issue tracker"))
  2265. )
  2266. title.setOpenExternalLinks(True)
  2267. closebtn = QtWidgets.QPushButton(_("Close"))
  2268. tab_widget = QtWidgets.QTabWidget()
  2269. description_label = QtWidgets.QLabel(
  2270. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2271. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2272. version=version,
  2273. beta=('BETA' if beta else ''),
  2274. date=version_date,
  2275. arch=platform.architecture()[0])
  2276. )
  2277. description_label.setOpenExternalLinks(True)
  2278. lic_lbl_header = QtWidgets.QLabel(
  2279. '%s:<br>%s<br>' % (
  2280. _('Licensed under the MIT license'),
  2281. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2282. "http://www.opensource.org/licenses/mit-license.php</a>"
  2283. )
  2284. )
  2285. lic_lbl_header.setOpenExternalLinks(True)
  2286. lic_lbl_body = QtWidgets.QLabel(
  2287. _(
  2288. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2289. 'of this software and associated documentation files (the "Software"), to deal\n'
  2290. 'in the Software without restriction, including without limitation the rights\n'
  2291. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2292. 'copies of the Software, and to permit persons to whom the Software is\n'
  2293. 'furnished to do so, subject to the following conditions:\n\n'
  2294. 'The above copyright notice and this permission notice shall be included in\n'
  2295. 'all copies or substantial portions of the Software.\n\n'
  2296. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2297. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2298. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2299. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2300. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2301. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2302. 'THE SOFTWARE.'
  2303. )
  2304. )
  2305. attributions_label = QtWidgets.QLabel(
  2306. _(
  2307. 'Some of the icons used are from the following sources:<br>'
  2308. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2309. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2310. 'title="Flaticon">www.flaticon.com</a></div>'
  2311. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2312. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2313. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2314. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2315. 'title="Flaticon">www.flaticon.com</a></div>'
  2316. )
  2317. )
  2318. attributions_label.setOpenExternalLinks(True)
  2319. # layouts
  2320. layout1 = QtWidgets.QVBoxLayout()
  2321. layout1_1 = QtWidgets.QHBoxLayout()
  2322. layout1_2 = QtWidgets.QHBoxLayout()
  2323. layout2 = QtWidgets.QHBoxLayout()
  2324. layout3 = QtWidgets.QHBoxLayout()
  2325. self.setLayout(layout1)
  2326. layout1.addLayout(layout1_1)
  2327. layout1.addLayout(layout1_2)
  2328. layout1.addLayout(layout2)
  2329. layout1.addLayout(layout3)
  2330. layout1_1.addStretch()
  2331. layout1_1.addWidget(description_label)
  2332. layout1_2.addWidget(tab_widget)
  2333. self.splash_tab = QtWidgets.QWidget()
  2334. self.splash_tab.setObjectName("splash_about")
  2335. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2336. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2337. tab_widget.addTab(self.splash_tab, _("Splash"))
  2338. self.programmmers_tab = QtWidgets.QWidget()
  2339. self.programmmers_tab.setObjectName("programmers_about")
  2340. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2341. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2342. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2343. self.translators_tab = QtWidgets.QWidget()
  2344. self.translators_tab.setObjectName("translators_about")
  2345. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2346. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2347. tab_widget.addTab(self.translators_tab, _("Translators"))
  2348. self.license_tab = QtWidgets.QWidget()
  2349. self.license_tab.setObjectName("license_about")
  2350. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2351. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2352. tab_widget.addTab(self.license_tab, _("License"))
  2353. self.attributions_tab = QtWidgets.QWidget()
  2354. self.attributions_tab.setObjectName("attributions_about")
  2355. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2356. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2357. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2358. self.splash_tab_layout.addWidget(logo, stretch=0)
  2359. self.splash_tab_layout.addWidget(title, stretch=1)
  2360. pal = QtGui.QPalette()
  2361. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2362. self.prog_grid_lay = QtWidgets.QGridLayout()
  2363. self.prog_grid_lay.setHorizontalSpacing(20)
  2364. self.prog_grid_lay.setColumnStretch(0, 0)
  2365. self.prog_grid_lay.setColumnStretch(2, 1)
  2366. prog_widget = QtWidgets.QWidget()
  2367. prog_widget.setLayout(self.prog_grid_lay)
  2368. prog_scroll = QtWidgets.QScrollArea()
  2369. prog_scroll.setWidget(prog_widget)
  2370. prog_scroll.setWidgetResizable(True)
  2371. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2372. prog_scroll.setPalette(pal)
  2373. self.programmmers_tab_layout.addWidget(prog_scroll)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2402. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2403. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2404. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2405. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2406. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2407. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2408. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2409. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2410. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2411. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2412. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2413. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2414. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2415. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2416. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2417. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2418. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2419. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2420. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2421. self.translator_grid_lay = QtWidgets.QGridLayout()
  2422. self.translator_grid_lay.setColumnStretch(0, 0)
  2423. self.translator_grid_lay.setColumnStretch(1, 0)
  2424. self.translator_grid_lay.setColumnStretch(2, 1)
  2425. self.translator_grid_lay.setColumnStretch(3, 0)
  2426. # trans_widget = QtWidgets.QWidget()
  2427. # trans_widget.setLayout(self.translator_grid_lay)
  2428. # self.translators_tab_layout.addWidget(trans_widget)
  2429. # self.translators_tab_layout.addStretch()
  2430. trans_widget = QtWidgets.QWidget()
  2431. trans_widget.setLayout(self.translator_grid_lay)
  2432. trans_scroll = QtWidgets.QScrollArea()
  2433. trans_scroll.setWidget(trans_widget)
  2434. trans_scroll.setWidgetResizable(True)
  2435. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2436. trans_scroll.setPalette(pal)
  2437. self.translators_tab_layout.addWidget(trans_scroll)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2449. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2450. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2451. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2452. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2453. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2454. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2455. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2456. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2457. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2458. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2459. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2460. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2461. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2462. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2463. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2464. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2465. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2466. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2467. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2468. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2469. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2470. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2471. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2472. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2473. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2474. self.translator_grid_lay.setColumnStretch(0, 0)
  2475. self.translators_tab_layout.addStretch()
  2476. self.license_tab_layout.addWidget(lic_lbl_header)
  2477. self.license_tab_layout.addWidget(lic_lbl_body)
  2478. self.license_tab_layout.addStretch()
  2479. self.attributions_tab_layout.addWidget(attributions_label)
  2480. self.attributions_tab_layout.addStretch()
  2481. layout3.addStretch()
  2482. layout3.addWidget(closebtn)
  2483. closebtn.clicked.connect(self.accept)
  2484. AboutDialog(app=self, parent=self.ui).exec_()
  2485. def on_howto(self):
  2486. """
  2487. Displays the "about" dialog found in the Menu --> Help.
  2488. :return: None
  2489. """
  2490. class HowtoDialog(QtWidgets.QDialog):
  2491. def __init__(self, app, parent=None):
  2492. QtWidgets.QDialog.__init__(self, parent)
  2493. self.app = app
  2494. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2495. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2496. "<b>click</b></a>"
  2497. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2498. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2499. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2500. # Icon and title
  2501. self.setWindowIcon(parent.app_icon)
  2502. self.setWindowTitle('%s ...' % _("How To"))
  2503. self.resize(750, 375)
  2504. logo = QtWidgets.QLabel()
  2505. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2506. # content = QtWidgets.QLabel(
  2507. # "%s<br>"
  2508. # "%s<br><br>"
  2509. # "%s,<br>"
  2510. # "%s<br>"
  2511. # "<ul>"
  2512. # "<li> &nbsp;%s %s</li>"
  2513. # "<li> &nbsp;%s %s</li>"
  2514. # "</ul>"
  2515. # "%s %s.<br>"
  2516. # "%s"
  2517. # "<ul>"
  2518. # "<li> &nbsp;%s &#128077;</li>"
  2519. # "<li> &nbsp;%s &#128513;</li>"
  2520. # "</ul>" %
  2521. # (
  2522. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2523. # _("Yet it cannot evolve without <b>contributions</b>."),
  2524. # _("If you want to see this application grow and become better and better"),
  2525. # _("you can <b>contribute</b> to the development yourself by:"),
  2526. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2527. # new_features_link,
  2528. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2529. # bugs_link,
  2530. # _("If you like or use this program you can make a donation"),
  2531. # donation_link,
  2532. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2533. # _("it will be welcomed with joy"),
  2534. # _("it will give me a reason to continue")
  2535. # )
  2536. # )
  2537. # font-weight: bold;
  2538. content = QtWidgets.QLabel(
  2539. "%s<br>"
  2540. "%s<br><br>"
  2541. "%s,<br>"
  2542. "%s<br>"
  2543. "<ul>"
  2544. "<li> &nbsp;%s %s</li>"
  2545. "<li> &nbsp;%s %s</li>"
  2546. "</ul>"
  2547. "<br><br>"
  2548. "%s <br>"
  2549. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2550. (
  2551. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2552. _("Yet it cannot evolve without <b>contributions</b>."),
  2553. _("If you want to see this application grow and become better and better"),
  2554. _("you can <b>contribute</b> to the development yourself by:"),
  2555. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2556. new_features_link,
  2557. _("Bug Reports by providing the steps required to reproduce the bug"),
  2558. bugs_link,
  2559. _("If you like what you have seen so far ..."),
  2560. _("Donations are NOT required."), _("But they are welcomed"),
  2561. donation_link
  2562. )
  2563. )
  2564. content.setOpenExternalLinks(True)
  2565. # palette
  2566. pal = QtGui.QPalette()
  2567. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2568. # layouts
  2569. main_layout = QtWidgets.QVBoxLayout()
  2570. self.setLayout(main_layout)
  2571. tab_layout = QtWidgets.QHBoxLayout()
  2572. buttons_hlay = QtWidgets.QHBoxLayout()
  2573. main_layout.addLayout(tab_layout)
  2574. main_layout.addLayout(buttons_hlay)
  2575. tab_widget = QtWidgets.QTabWidget()
  2576. tab_layout.addWidget(tab_widget)
  2577. closebtn = QtWidgets.QPushButton(_("Close"))
  2578. buttons_hlay.addStretch()
  2579. buttons_hlay.addWidget(closebtn)
  2580. # CONTRIBUTE section
  2581. self.intro_tab = QtWidgets.QWidget()
  2582. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2583. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2584. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2585. self.grid_lay = QtWidgets.QGridLayout()
  2586. self.grid_lay.setHorizontalSpacing(20)
  2587. self.grid_lay.setColumnStretch(0, 0)
  2588. self.grid_lay.setColumnStretch(1, 1)
  2589. intro_wdg = QtWidgets.QWidget()
  2590. intro_wdg.setLayout(self.grid_lay)
  2591. intro_scroll_area = QtWidgets.QScrollArea()
  2592. intro_scroll_area.setWidget(intro_wdg)
  2593. intro_scroll_area.setWidgetResizable(True)
  2594. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2595. intro_scroll_area.setPalette(pal)
  2596. self.grid_lay.addWidget(logo, 0, 0)
  2597. self.grid_lay.addWidget(content, 0, 1)
  2598. self.intro_tab_layout.addWidget(intro_scroll_area)
  2599. # LINKS EXCHANGE section
  2600. self.links_tab = QtWidgets.QWidget()
  2601. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2602. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2603. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2604. self.links_lay = QtWidgets.QHBoxLayout()
  2605. links_wdg = QtWidgets.QWidget()
  2606. links_wdg.setLayout(self.links_lay)
  2607. links_scroll_area = QtWidgets.QScrollArea()
  2608. links_scroll_area.setWidget(links_wdg)
  2609. links_scroll_area.setWidgetResizable(True)
  2610. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2611. links_scroll_area.setPalette(pal)
  2612. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2613. self.links_tab_layout.addWidget(links_scroll_area)
  2614. # HOW TO section
  2615. self.howto_tab = QtWidgets.QWidget()
  2616. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2617. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2618. tab_widget.addTab(self.howto_tab, _("How To's"))
  2619. self.howto_lay = QtWidgets.QHBoxLayout()
  2620. howto_wdg = QtWidgets.QWidget()
  2621. howto_wdg.setLayout(self.howto_lay)
  2622. howto_scroll_area = QtWidgets.QScrollArea()
  2623. howto_scroll_area.setWidget(howto_wdg)
  2624. howto_scroll_area.setWidgetResizable(True)
  2625. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2626. howto_scroll_area.setPalette(pal)
  2627. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2628. self.howto_tab_layout.addWidget(howto_scroll_area)
  2629. # BUTTONS section
  2630. closebtn.clicked.connect(self.accept)
  2631. HowtoDialog(app=self, parent=self.ui).exec_()
  2632. def install_bookmarks(self, book_dict=None):
  2633. """
  2634. Install the bookmarks actions in the Help menu -> Bookmarks
  2635. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2636. :return: None
  2637. """
  2638. if book_dict is None:
  2639. self.defaults["global_bookmarks"].update(
  2640. {
  2641. '1': ['FlatCAM', "http://flatcam.org"],
  2642. '2': [_('Backup Site'), ""]
  2643. }
  2644. )
  2645. else:
  2646. self.defaults["global_bookmarks"].clear()
  2647. self.defaults["global_bookmarks"].update(book_dict)
  2648. # first try to disconnect if somehow they get connected from elsewhere
  2649. for act in self.ui.menuhelp_bookmarks.actions():
  2650. try:
  2651. act.triggered.disconnect()
  2652. except TypeError:
  2653. pass
  2654. # clear all actions except the last one who is the Bookmark manager
  2655. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2656. pass
  2657. else:
  2658. self.ui.menuhelp_bookmarks.removeAction(act)
  2659. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2660. if self.defaults["global_bookmarks"]:
  2661. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2662. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2663. # the JSON is first making the keys as strings (therefore I have to use strings too
  2664. # or do the conversion :(
  2665. # )
  2666. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2667. # the '10' entry jsut after '1' therefore ordering as strings
  2668. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2669. key=lambda x: int(x[0]))
  2670. for entry, bookmark in sorted_bookmarks:
  2671. title = bookmark[0]
  2672. weblink = bookmark[1]
  2673. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2674. act.setText(title)
  2675. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2676. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2677. if title == _('Backup Site') and weblink == "":
  2678. act.triggered.connect(self.on_backup_site)
  2679. else:
  2680. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2681. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2682. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2683. def on_bookmarks_manager(self):
  2684. """
  2685. Adds the bookmark manager in a Tab in Plot Area
  2686. :return:
  2687. """
  2688. for idx in range(self.ui.plot_tab_area.count()):
  2689. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2690. # there can be only one instance of Bookmark Manager at one time
  2691. return
  2692. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2693. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2694. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2695. # add the tab if it was closed
  2696. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2697. # delete the absolute and relative position and messages in the infobar
  2698. # self.ui.position_label.setText("")
  2699. # self.ui.rel_position_label.setText("")
  2700. # hide coordinates toolbars in the infobar while in DB
  2701. self.ui.coords_toolbar.hide()
  2702. self.ui.delta_coords_toolbar.hide()
  2703. # Switch plot_area to preferences page
  2704. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2705. def on_backup_site(self):
  2706. msgbox = QtWidgets.QMessageBox()
  2707. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2708. "1. FlatCAM.org website is down\n"
  2709. "2. Someone forked FlatCAM project and wants to point\n"
  2710. "to his own website\n\n"
  2711. "If you can't get any informations about the application\n"
  2712. "use the YouTube channel link from the Help menu."))
  2713. msgbox.setWindowTitle(_("Alternative website"))
  2714. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2715. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2716. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2717. msgbox.setDefaultButton(bt_yes)
  2718. msgbox.exec_()
  2719. # response = msgbox.clickedButton()
  2720. def final_save(self):
  2721. """
  2722. Callback for doing a preferences save to file whenever the application is about to quit.
  2723. If the project has changes, it will ask the user to save the project.
  2724. :return: None
  2725. """
  2726. if self.save_in_progress:
  2727. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2728. return
  2729. if self.should_we_save and self.collection.get_list():
  2730. msgbox = QtWidgets.QMessageBox()
  2731. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2732. "\n"
  2733. "Do you want to Save the project?"))
  2734. msgbox.setWindowTitle(_("Save changes"))
  2735. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2736. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2737. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2738. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2739. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2740. msgbox.setDefaultButton(bt_yes)
  2741. msgbox.exec_()
  2742. response = msgbox.clickedButton()
  2743. if response == bt_yes:
  2744. try:
  2745. self.trayIcon.hide()
  2746. except Exception:
  2747. pass
  2748. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2749. elif response == bt_no:
  2750. try:
  2751. self.trayIcon.hide()
  2752. except Exception:
  2753. pass
  2754. self.quit_application()
  2755. elif response == bt_cancel:
  2756. return
  2757. else:
  2758. try:
  2759. self.trayIcon.hide()
  2760. except Exception:
  2761. pass
  2762. self.quit_application()
  2763. def quit_application(self):
  2764. """
  2765. Called (as a pyslot or not) when the application is quit.
  2766. :return: None
  2767. """
  2768. # close editors before quiting the app, if they are open
  2769. if self.geo_editor.editor_active is True:
  2770. self.geo_editor.deactivate()
  2771. try:
  2772. self.geo_editor.disconnect()
  2773. except TypeError:
  2774. pass
  2775. self.log.debug("App.quit_application() --> Geo Editor deactivated.")
  2776. if self.exc_editor.editor_active is True:
  2777. self.exc_editor.deactivate()
  2778. try:
  2779. self.grb_editor.disconnect()
  2780. except TypeError:
  2781. pass
  2782. self.log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2783. if self.grb_editor.editor_active is True:
  2784. self.grb_editor.deactivate_grb_editor()
  2785. try:
  2786. self.exc_editor.disconnect()
  2787. except TypeError:
  2788. pass
  2789. self.log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2790. # disconnect the mouse events
  2791. if self.is_legacy:
  2792. self.plotcanvas.graph_event_disconnect(self.mm)
  2793. self.plotcanvas.graph_event_disconnect(self.mp)
  2794. self.plotcanvas.graph_event_disconnect(self.mr)
  2795. self.plotcanvas.graph_event_disconnect(self.mdc)
  2796. self.plotcanvas.graph_event_disconnect(self.kp)
  2797. else:
  2798. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2799. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2800. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2801. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2802. self.on_mouse_double_click_over_plot)
  2803. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2804. self.preferencesUiManager.save_defaults(silent=True)
  2805. self.log.debug("App.quit_application() --> App Defaults saved.")
  2806. if self.cmd_line_headless != 1:
  2807. # save app state to file
  2808. stgs = QSettings("Open Source", "FlatCAM")
  2809. stgs.setValue('saved_gui_state', self.ui.saveState())
  2810. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2811. stgs.setValue(
  2812. 'language',
  2813. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2814. )
  2815. stgs.setValue(
  2816. 'notebook_font_size',
  2817. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2818. )
  2819. stgs.setValue(
  2820. 'axis_font_size',
  2821. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2822. )
  2823. stgs.setValue(
  2824. 'textbox_font_size',
  2825. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2826. )
  2827. stgs.setValue(
  2828. 'hud_font_size',
  2829. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2830. )
  2831. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2832. stgs.setValue(
  2833. 'machinist',
  2834. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2835. )
  2836. # This will write the setting to the platform specific storage.
  2837. del stgs
  2838. self.log.debug("App.quit_application() --> App UI state saved.")
  2839. # try to quit the Socket opened by ArgsThread class
  2840. try:
  2841. # self.new_launch.thread_exit = True
  2842. # self.new_launch.listener.close()
  2843. self.new_launch.stop.emit()
  2844. except Exception as err:
  2845. self.log.debug("App.quit_application() --> %s" % str(err))
  2846. # try to quit the QThread that run ArgsThread class
  2847. try:
  2848. # del self.new_launch
  2849. self.listen_th.quit()
  2850. except Exception as e:
  2851. self.log.debug("App.quit_application() --> %s" % str(e))
  2852. # terminate workers
  2853. # self.workers.__del__()
  2854. self.clear_pool()
  2855. # quit app by signalling for self.kill_app() method
  2856. # self.close_app_signal.emit()
  2857. QtWidgets.qApp.quit()
  2858. sys.exit(0)
  2859. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2860. # we use the following command
  2861. # minor_v = sys.version_info.minor
  2862. # if minor_v < 8:
  2863. # # make sure that the app closes
  2864. # sys.exit(0)
  2865. # else:
  2866. # os._exit(0) # fix to work with Python 3.8
  2867. @staticmethod
  2868. def kill_app():
  2869. QtWidgets.qApp.quit()
  2870. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2871. # we use the following command
  2872. sys.exit(0)
  2873. def on_portable_checked(self, state):
  2874. """
  2875. Callback called when the checkbox in Preferences GUI is checked.
  2876. It will set the application as portable by creating the preferences and recent files in the
  2877. 'config' folder found in the FlatCAM installation folder.
  2878. :param state: boolean, the state of the checkbox when clicked/checked
  2879. :return:
  2880. """
  2881. line_no = 0
  2882. data = None
  2883. if sys.platform != 'win32':
  2884. # this won't work in Linux or MacOS
  2885. return
  2886. # test if the app was frozen and choose the path for the configuration file
  2887. if getattr(sys, "frozen", False) is True:
  2888. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2889. else:
  2890. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2891. config_file = current_data_path + '\\configuration.txt'
  2892. try:
  2893. with open(config_file, 'r') as f:
  2894. try:
  2895. data = f.readlines()
  2896. except Exception as e:
  2897. self.log.debug('App.__init__() -->%s' % str(e))
  2898. return
  2899. except FileNotFoundError:
  2900. pass
  2901. for line in data:
  2902. line = line.strip('\n')
  2903. param = str(line).rpartition('=')
  2904. if param[0] == 'portable':
  2905. break
  2906. line_no += 1
  2907. if state:
  2908. data[line_no] = 'portable=True\n'
  2909. # create the new defauults files
  2910. # create current_defaults.FlatConfig file if there is none
  2911. try:
  2912. f = open(current_data_path + '/current_defaults.FlatConfig')
  2913. f.close()
  2914. except IOError:
  2915. self.log.debug('Creating empty current_defaults.FlatConfig')
  2916. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2917. json.dump({}, f)
  2918. f.close()
  2919. # create factory_defaults.FlatConfig file if there is none
  2920. try:
  2921. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2922. f.close()
  2923. except IOError:
  2924. self.log.debug('Creating empty factory_defaults.FlatConfig')
  2925. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2926. json.dump({}, f)
  2927. f.close()
  2928. try:
  2929. f = open(current_data_path + '/recent.json')
  2930. f.close()
  2931. except IOError:
  2932. self.log.debug('Creating empty recent.json')
  2933. f = open(current_data_path + '/recent.json', 'w')
  2934. json.dump([], f)
  2935. f.close()
  2936. try:
  2937. fp = open(current_data_path + '/recent_projects.json')
  2938. fp.close()
  2939. except IOError:
  2940. self.log.debug('Creating empty recent_projects.json')
  2941. fp = open(current_data_path + '/recent_projects.json', 'w')
  2942. json.dump([], fp)
  2943. fp.close()
  2944. # save the current defaults to the new defaults file
  2945. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2946. else:
  2947. data[line_no] = 'portable=False\n'
  2948. with open(config_file, 'w') as f:
  2949. f.writelines(data)
  2950. def on_register_files(self, obj_type=None):
  2951. """
  2952. Called whenever there is a need to register file extensions with FlatCAM.
  2953. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2954. :param obj_type: the type of object to be register for.
  2955. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2956. :return: None
  2957. """
  2958. self.log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2959. new_reg_path = 'Software\\Classes\\'
  2960. # find if the current user is admin
  2961. try:
  2962. is_admin = os.getuid() == 0
  2963. except AttributeError:
  2964. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2965. if is_admin is True:
  2966. root_path = winreg.HKEY_LOCAL_MACHINE
  2967. else:
  2968. root_path = winreg.HKEY_CURRENT_USER
  2969. # create the keys
  2970. def set_reg(name, root_pth, new_reg_path_par, value):
  2971. try:
  2972. winreg.CreateKey(root_pth, new_reg_path_par)
  2973. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  2974. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2975. return True
  2976. except WindowsError:
  2977. return False
  2978. # delete key in registry
  2979. def delete_reg(root_pth, reg_path, key_to_del):
  2980. key_to_del_path = reg_path + key_to_del
  2981. try:
  2982. winreg.DeleteKey(root_pth, key_to_del_path)
  2983. return True
  2984. except WindowsError:
  2985. return False
  2986. if obj_type is None or obj_type == 'excellon':
  2987. exc_list = \
  2988. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2989. exc_list = [x for x in exc_list if x != '']
  2990. # register all keys in the Preferences window
  2991. for ext in exc_list:
  2992. new_k = new_reg_path + '.%s' % ext
  2993. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2994. # and unregister those that are no longer in the Preferences windows but are in the file
  2995. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2996. if ext not in exc_list:
  2997. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2998. # now write the updated extensions to the self.defaults
  2999. # new_ext = ''
  3000. # for ext in exc_list:
  3001. # new_ext = new_ext + ext + ', '
  3002. # self.defaults["fa_excellon"] = new_ext
  3003. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3004. if obj_type is None or obj_type == 'gcode':
  3005. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3006. gco_list = [x for x in gco_list if x != '']
  3007. # register all keys in the Preferences window
  3008. for ext in gco_list:
  3009. new_k = new_reg_path + '.%s' % ext
  3010. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3011. # and unregister those that are no longer in the Preferences windows but are in the file
  3012. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3013. if ext not in gco_list:
  3014. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3015. # now write the updated extensions to the self.defaults
  3016. # new_ext = ''
  3017. # for ext in gco_list:
  3018. # new_ext = new_ext + ext + ', '
  3019. # self.defaults["fa_gcode"] = new_ext
  3020. self.inform.emit('[success] %s' %
  3021. _("Selected GCode file extensions registered with FlatCAM."))
  3022. if obj_type is None or obj_type == 'gerber':
  3023. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3024. grb_list = [x for x in grb_list if x != '']
  3025. # register all keys in the Preferences window
  3026. for ext in grb_list:
  3027. new_k = new_reg_path + '.%s' % ext
  3028. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3029. # and unregister those that are no longer in the Preferences windows but are in the file
  3030. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3031. if ext not in grb_list:
  3032. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3033. # now write the updated extensions to the self.defaults
  3034. # new_ext = ''
  3035. # for ext in grb_list:
  3036. # new_ext = new_ext + ext + ', '
  3037. # self.defaults["fa_gerber"] = new_ext
  3038. self.inform.emit('[success] %s' %
  3039. _("Selected Gerber file extensions registered with FlatCAM."))
  3040. def add_extension(self, ext_type):
  3041. """
  3042. Add a file extension to the list for a specific object
  3043. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3044. :return:
  3045. """
  3046. if ext_type == 'excellon':
  3047. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3048. if new_ext == '':
  3049. return
  3050. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3051. if new_ext in old_val:
  3052. return
  3053. old_val.append(new_ext)
  3054. old_val.sort()
  3055. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3056. if ext_type == 'gcode':
  3057. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3058. if new_ext == '':
  3059. return
  3060. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3061. if new_ext in old_val:
  3062. return
  3063. old_val.append(new_ext)
  3064. old_val.sort()
  3065. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3066. if ext_type == 'gerber':
  3067. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3068. if new_ext == '':
  3069. return
  3070. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3071. if new_ext in old_val:
  3072. return
  3073. old_val.append(new_ext)
  3074. old_val.sort()
  3075. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3076. if ext_type == 'keyword':
  3077. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3078. if new_kw == '':
  3079. return
  3080. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3081. if new_kw in old_val:
  3082. return
  3083. old_val.append(new_kw)
  3084. old_val.sort()
  3085. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3086. # update the self.myKeywords so the model is updated
  3087. self.autocomplete_kw_list = \
  3088. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3089. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3090. self.shell.command_line().set_model_data(self.myKeywords)
  3091. def del_extension(self, ext_type):
  3092. """
  3093. Remove a file extension from the list for a specific object
  3094. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3095. :return:
  3096. """
  3097. if ext_type == 'excellon':
  3098. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3099. if new_ext == '':
  3100. return
  3101. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3102. if new_ext not in old_val:
  3103. return
  3104. old_val.remove(new_ext)
  3105. old_val.sort()
  3106. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3107. if ext_type == 'gcode':
  3108. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3109. if new_ext == '':
  3110. return
  3111. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3112. if new_ext not in old_val:
  3113. return
  3114. old_val.remove(new_ext)
  3115. old_val.sort()
  3116. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3117. if ext_type == 'gerber':
  3118. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3119. if new_ext == '':
  3120. return
  3121. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3122. if new_ext not in old_val:
  3123. return
  3124. old_val.remove(new_ext)
  3125. old_val.sort()
  3126. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3127. if ext_type == 'keyword':
  3128. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3129. if new_kw == '':
  3130. return
  3131. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3132. if new_kw not in old_val:
  3133. return
  3134. old_val.remove(new_kw)
  3135. old_val.sort()
  3136. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3137. # update the self.myKeywords so the model is updated
  3138. self.autocomplete_kw_list = \
  3139. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3140. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3141. self.shell.command_line().set_model_data(self.myKeywords)
  3142. def restore_extensions(self, ext_type):
  3143. """
  3144. Restore all file extensions associations with FlatCAM, for a specific object
  3145. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3146. :return:
  3147. """
  3148. if ext_type == 'excellon':
  3149. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3150. # for the ability to open Excellon files with .txt extension
  3151. new_exc_list = deepcopy(self.exc_list)
  3152. try:
  3153. new_exc_list.remove('txt')
  3154. except ValueError:
  3155. pass
  3156. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3157. if ext_type == 'gcode':
  3158. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3159. if ext_type == 'gerber':
  3160. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3161. if ext_type == 'keyword':
  3162. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3163. # update the self.myKeywords so the model is updated
  3164. self.autocomplete_kw_list = self.default_keywords
  3165. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3166. self.shell.commnad_line().set_model_data(self.myKeywords)
  3167. def delete_all_extensions(self, ext_type):
  3168. """
  3169. Delete all file extensions associations with FlatCAM, for a specific object
  3170. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3171. :return:
  3172. """
  3173. if ext_type == 'excellon':
  3174. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3175. if ext_type == 'gcode':
  3176. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3177. if ext_type == 'gerber':
  3178. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3179. if ext_type == 'keyword':
  3180. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3181. # update the self.myKeywords so the model is updated
  3182. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3183. self.shell.command_line().set_model_data(self.myKeywords)
  3184. def on_edit_join(self, name=None):
  3185. """
  3186. Callback for Edit->Join. Joins the selected geometry objects into
  3187. a new one.
  3188. :return: None
  3189. """
  3190. self.defaults.report_usage("on_edit_join()")
  3191. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3192. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3193. geo_type_set = set()
  3194. objs = self.collection.get_selected()
  3195. if len(objs) < 2:
  3196. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3197. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3198. return 'fail'
  3199. for obj in objs:
  3200. geo_type_set.add(obj.multigeo)
  3201. # if len(geo_type_list) == 1 means that all list elements are the same
  3202. if len(geo_type_set) != 1:
  3203. self.inform.emit('[ERROR] %s' %
  3204. _("Failed join. The Geometry objects are of different types.\n"
  3205. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3206. "convert from one to another and retry joining \n"
  3207. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3208. "the result may not be what was expected. \n"
  3209. "Check the generated GCODE."))
  3210. return
  3211. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3212. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3213. if True in geo_type_set:
  3214. def initialize(geo_obj, app):
  3215. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3216. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3217. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3218. for v in geo_obj.tools.values():
  3219. v['data']['name'] = obj_name_multi
  3220. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3221. else:
  3222. def initialize(geo_obj, app):
  3223. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3224. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3225. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3226. for v in geo_obj.tools.values():
  3227. v['data']['name'] = obj_name_single
  3228. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3229. self.should_we_save = True
  3230. def on_edit_join_exc(self):
  3231. """
  3232. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3233. a new Excellon.
  3234. :return: None
  3235. """
  3236. self.defaults.report_usage("on_edit_join_exc()")
  3237. objs = self.collection.get_selected()
  3238. for obj in objs:
  3239. if not isinstance(obj, ExcellonObject):
  3240. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3241. return
  3242. if len(objs) < 2:
  3243. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3244. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3245. return 'fail'
  3246. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3247. def initialize(exc_obj, app):
  3248. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3249. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3250. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3251. self.should_we_save = True
  3252. def on_edit_join_grb(self):
  3253. """
  3254. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3255. a new Gerber object.
  3256. :return: None
  3257. """
  3258. self.defaults.report_usage("on_edit_join_grb()")
  3259. objs = self.collection.get_selected()
  3260. for obj in objs:
  3261. if not isinstance(obj, GerberObject):
  3262. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3263. return
  3264. if len(objs) < 2:
  3265. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3266. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3267. return 'fail'
  3268. def initialize(grb_obj, app):
  3269. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3270. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3271. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3272. self.should_we_save = True
  3273. def on_convert_singlegeo_to_multigeo(self):
  3274. """
  3275. Called for converting a Geometry object from single-geo to multi-geo.
  3276. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3277. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3278. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3279. the solid-geometry of that tool.
  3280. :return: None
  3281. """
  3282. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3283. obj = self.collection.get_active()
  3284. if obj is None:
  3285. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3286. return
  3287. if not isinstance(obj, GeometryObject):
  3288. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3289. return
  3290. obj.multigeo = True
  3291. for tooluid, dict_value in obj.tools.items():
  3292. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3293. if not isinstance(obj.solid_geometry, list):
  3294. obj.solid_geometry = [obj.solid_geometry]
  3295. # obj.solid_geometry[:] = []
  3296. obj.plot()
  3297. self.should_we_save = True
  3298. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3299. def on_convert_multigeo_to_singlegeo(self):
  3300. """
  3301. Called for converting a Geometry object from multi-geo to single-geo.
  3302. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3303. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3304. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3305. the solid-geometry of that tool.
  3306. :return: None
  3307. """
  3308. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3309. obj = self.collection.get_active()
  3310. if obj is None:
  3311. self.inform.emit('[ERROR_NOTCL] %s' %
  3312. _("Failed. Select a Geometry Object and try again."))
  3313. return
  3314. if not isinstance(obj, GeometryObject):
  3315. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3316. (_("Expected a GeometryObject, got"), type(obj)))
  3317. return
  3318. obj.multigeo = False
  3319. total_solid_geometry = []
  3320. for tooluid, dict_value in obj.tools.items():
  3321. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3322. # clear the original geometry
  3323. dict_value['solid_geometry'][:] = []
  3324. obj.solid_geometry = deepcopy(total_solid_geometry)
  3325. obj.plot()
  3326. self.should_we_save = True
  3327. self.inform.emit('[success] %s' %
  3328. _("A Geometry object was converted to SingleGeo type."))
  3329. def on_defaults_dict_change(self, field):
  3330. """
  3331. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3332. Edit -> Preferences tab window.
  3333. :param field: the key of the self.defaults dictionary that was changed.
  3334. :return: None
  3335. """
  3336. self.preferencesUiManager.defaults_write_form_field(field=field)
  3337. if field == "units":
  3338. self.set_screen_units(self.defaults['units'])
  3339. def set_screen_units(self, units):
  3340. """
  3341. Set the FlatCAM units on the status bar.
  3342. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3343. :return: None
  3344. """
  3345. self.ui.units_label.setText("[" + units.lower() + "]")
  3346. def on_toggle_units_click(self):
  3347. try:
  3348. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3349. except (TypeError, AttributeError):
  3350. pass
  3351. if self.defaults["units"] == 'MM':
  3352. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3353. else:
  3354. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3355. self.on_toggle_units(no_pref=True)
  3356. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3357. lambda: self.on_toggle_units(no_pref=False))
  3358. def scale_defaults(self, sfactor, dimensions):
  3359. for dim in dimensions:
  3360. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3361. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3362. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3363. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3364. if not self.defaults[dim] or self.defaults[dim] == '':
  3365. continue
  3366. if isinstance(self.defaults[dim], str):
  3367. try:
  3368. tools_diameters = eval(self.defaults[dim])
  3369. except Exception as e:
  3370. self.log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3371. continue
  3372. elif isinstance(self.defaults[dim], (float, int)):
  3373. tools_diameters = [self.defaults[dim]]
  3374. else:
  3375. tools_diameters = list(self.defaults[dim])
  3376. if isinstance(tools_diameters, (tuple, list)):
  3377. pass
  3378. elif isinstance(tools_diameters, (int, float)):
  3379. tools_diameters = [self.defaults[dim]]
  3380. else:
  3381. continue
  3382. td_len = len(tools_diameters)
  3383. conv_list = []
  3384. for t in range(td_len):
  3385. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3386. self.defaults[dim] = conv_list
  3387. elif dim in ['global_gridx', 'global_gridy']:
  3388. # format the number of decimals to the one specified in self.decimals
  3389. try:
  3390. val = float(self.defaults[dim]) * sfactor
  3391. except Exception as e:
  3392. self.log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3393. continue
  3394. self.defaults[dim] = self.dec_format(val, self.decimals)
  3395. else:
  3396. # the number of decimals for the rest is kept unchanged
  3397. if self.defaults[dim]:
  3398. try:
  3399. val = float(self.defaults[dim]) * sfactor
  3400. except Exception as e:
  3401. self.log.debug(
  3402. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3403. )
  3404. continue
  3405. self.defaults[dim] = self.dec_format(val, self.decimals)
  3406. def on_toggle_units(self, no_pref=False):
  3407. """
  3408. Callback for the Units radio-button change in the Preferences tab.
  3409. Changes the application's default units adn for the project too.
  3410. If changing the project's units, the change propagates to all of
  3411. the objects in the project.
  3412. :return: None
  3413. """
  3414. self.defaults.report_usage("on_toggle_units")
  3415. if self.toggle_units_ignore:
  3416. return
  3417. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3418. # If option is the same, then ignore
  3419. if new_units == self.defaults["units"].upper():
  3420. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3421. return
  3422. # Keys in self.defaults for which to scale their values
  3423. dimensions = [
  3424. # Global
  3425. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3426. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3427. # Gerber Object
  3428. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3429. # Gerber Editor
  3430. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3431. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3432. # Excellon Object
  3433. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3434. # Excellon Editor
  3435. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3436. "excellon_editor_slot_length",
  3437. # Geometry Object
  3438. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3439. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3440. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3441. "geometry_extracut_length", "geometry_z_pdepth",
  3442. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3443. # CNCJob Object
  3444. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3445. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3446. # Isolation Tool
  3447. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3448. # Drilling Tool
  3449. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3450. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3451. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3452. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3453. # NCC Tool
  3454. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3455. "tools_ncc_newdia",
  3456. # Cutout Tool
  3457. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3458. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3459. # Paint Tool
  3460. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3461. # 2Sided Tool
  3462. "tools_2sided_drilldia",
  3463. # Film Tool
  3464. "tools_film_boundary", "tools_film_scale_stroke",
  3465. # Panel Tool
  3466. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3467. "tools_panelize_constrainy",
  3468. # Calculators Tool
  3469. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3470. # Transform Tool
  3471. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3472. "tools_transform_buffer_dis",
  3473. # SolderPaste Tool
  3474. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3475. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3476. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3477. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3478. # Corner Markers Tool
  3479. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3480. # Check Rules Tool
  3481. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3482. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3483. # QRCode Tool
  3484. "tools_qrcode_border_size",
  3485. # Copper Thieving Tool
  3486. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3487. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3488. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3489. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3490. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3491. "tools_copper_thieving_mask_clearance",
  3492. # Fiducials Tool
  3493. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3494. # Calibration Tool
  3495. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3496. # Drills Extraction Tool
  3497. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3498. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3499. # Punch Gerber Tool
  3500. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3501. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3502. # Invert Gerber Tool
  3503. "tools_invert_margin",
  3504. ]
  3505. # The scaling factor depending on choice of units.
  3506. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3507. # Changing project units. Warn user.
  3508. msgbox = QtWidgets.QMessageBox()
  3509. msgbox.setWindowTitle(_("Toggle Units"))
  3510. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3511. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3512. msgbox.setText(_("Changing the units of the project\n"
  3513. "will scale all objects.\n\n"
  3514. "Do you want to continue?"))
  3515. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3516. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3517. msgbox.setDefaultButton(bt_ok)
  3518. msgbox.exec_()
  3519. response = msgbox.clickedButton()
  3520. if response == bt_ok:
  3521. if no_pref is False:
  3522. self.preferencesUiManager.defaults_read_form()
  3523. self.scale_defaults(factor, dimensions)
  3524. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3525. self.defaults["units"] = new_units
  3526. # update the defaults from form, some may assume that the conversion is enough and it's not
  3527. self.on_options_app2project()
  3528. # update the objects
  3529. for obj in self.collection.get_list():
  3530. obj.convert_units(new_units)
  3531. # make that the properties stored in the object are also updated
  3532. self.app_obj.object_changed.emit(obj)
  3533. # rebuild the object UI
  3534. obj.build_ui()
  3535. # change this only if the workspace is active
  3536. if self.defaults['global_workspace'] is True:
  3537. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3538. # adjust the grid values on the main toolbar
  3539. val_x = float(self.defaults['global_gridx']) * factor
  3540. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3541. current = self.collection.get_active()
  3542. if current is not None:
  3543. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3544. if not isinstance(current, GeometryObject):
  3545. current.to_form()
  3546. # replot all objects
  3547. self.plot_all()
  3548. # set the status labels to reflect the current FlatCAM units
  3549. self.set_screen_units(new_units)
  3550. # signal to the app that we changed the object properties and it should save the project
  3551. self.should_we_save = True
  3552. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3553. else:
  3554. # Undo toggling
  3555. self.toggle_units_ignore = True
  3556. if self.defaults['units'].upper() == 'MM':
  3557. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3558. else:
  3559. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3560. self.toggle_units_ignore = False
  3561. # store the grid values so they are not changed in the next step
  3562. val_x = float(self.defaults['global_gridx'])
  3563. val_y = float(self.defaults['global_gridy'])
  3564. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3565. self.preferencesUiManager.defaults_read_form()
  3566. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3567. # in self.defaults from the GUI elements but
  3568. # I don't want it for the grid values, so I update them here
  3569. self.defaults['global_gridx'] = val_x
  3570. self.defaults['global_gridy'] = val_y
  3571. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3572. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3573. def on_deselect_all(self):
  3574. self.collection.set_all_inactive()
  3575. self.delete_selection_shape()
  3576. def on_workspace_modified(self):
  3577. # self.save_defaults(silent=True)
  3578. self.plotcanvas.delete_workspace()
  3579. self.preferencesUiManager.defaults_read_form()
  3580. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3581. def on_workspace(self):
  3582. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3583. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3584. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3585. else:
  3586. self.plotcanvas.delete_workspace()
  3587. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3588. self.preferencesUiManager.defaults_read_form()
  3589. # self.save_defaults(silent=True)
  3590. def on_workspace_toggle(self):
  3591. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3592. try:
  3593. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3594. except TypeError:
  3595. pass
  3596. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3597. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3598. self.on_workspace()
  3599. def on_cursor_type(self, val):
  3600. """
  3601. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3602. :return: None
  3603. """
  3604. self.app_cursor.enabled = False
  3605. if val == 'small':
  3606. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3607. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3608. self.app_cursor = self.plotcanvas.new_cursor()
  3609. else:
  3610. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3611. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3612. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3613. if self.ui.grid_snap_btn.isChecked():
  3614. self.app_cursor.enabled = True
  3615. else:
  3616. self.app_cursor.enabled = False
  3617. def on_tool_add_keypress(self):
  3618. # ## Current application units in Upper Case
  3619. self.units = self.defaults['units'].upper()
  3620. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3621. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3622. if notebook_widget_name == 'properties_tab':
  3623. if self.collection.get_active().kind == 'geometry':
  3624. # Tool add works for Geometry only if Advanced is True in Preferences
  3625. if self.defaults["global_app_level"] == 'a':
  3626. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3627. text='%s:' % _('Enter a Tool Diameter'),
  3628. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3629. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3630. tool_add_popup.wdg.selectAll()
  3631. val, ok = tool_add_popup.get_value()
  3632. if ok:
  3633. if float(val) == 0:
  3634. self.inform.emit('[WARNING_NOTCL] %s' %
  3635. _("Please enter a tool diameter with non-zero value, in Float format."))
  3636. return
  3637. self.collection.get_active().on_tool_add(clicked_state=False, dia=float(val))
  3638. else:
  3639. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3640. else:
  3641. msgbox = QtWidgets.QMessageBox()
  3642. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3643. "Go to Preferences -> General - Show Advanced Options."))
  3644. msgbox.setWindowTitle("Tool adding ...")
  3645. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3646. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3647. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3648. msgbox.setDefaultButton(bt_ok)
  3649. msgbox.exec_()
  3650. # work only if the notebook tab on focus is the Tools_Tab
  3651. if notebook_widget_name == 'tool_tab':
  3652. try:
  3653. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3654. except AttributeError:
  3655. return
  3656. # and only if the tool is NCC Tool
  3657. if tool_widget == self.ncclear_tool.toolName:
  3658. self.ncclear_tool.on_add_tool_by_key()
  3659. # and only if the tool is Paint Area Tool
  3660. elif tool_widget == self.paint_tool.toolName:
  3661. self.paint_tool.on_add_tool_by_key()
  3662. # and only if the tool is Solder Paste Dispensing Tool
  3663. elif tool_widget == self.paste_tool.toolName:
  3664. self.paste_tool.on_add_tool_by_key()
  3665. # and only if the tool is Isolation Tool
  3666. elif tool_widget == self.isolation_tool.toolName:
  3667. self.isolation_tool.on_add_tool_by_key()
  3668. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3669. # See description below.
  3670. def on_delete_keypress(self):
  3671. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3672. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3673. if notebook_widget_name == 'properties_tab':
  3674. if self.collection.get_active().kind == 'geometry':
  3675. self.collection.get_active().on_tool_delete()
  3676. # work only if the notebook tab on focus is the Tools_Tab
  3677. elif notebook_widget_name == 'tool_tab':
  3678. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3679. # and only if the tool is NCC Tool
  3680. if tool_widget == self.ncclear_tool.toolName:
  3681. self.ncclear_tool.on_tool_delete()
  3682. # and only if the tool is Paint Tool
  3683. elif tool_widget == self.paint_tool.toolName:
  3684. self.paint_tool.on_tool_delete()
  3685. # and only if the tool is Solder Paste Dispensing Tool
  3686. elif tool_widget == self.paste_tool.toolName:
  3687. self.paste_tool.on_tool_delete()
  3688. # and only if the tool is Isolation Tool
  3689. elif tool_widget == self.isolation_tool.toolName:
  3690. self.isolation_tool.on_tool_delete()
  3691. else:
  3692. self.on_delete()
  3693. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3694. # some screens you have to be careful where you hover with your mouse.
  3695. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3696. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3697. # Complicated, I know :)
  3698. def on_delete(self, force_deletion=False):
  3699. """
  3700. Delete the currently selected FlatCAMObjs.
  3701. :param force_deletion: used by Tcl command
  3702. :return: None
  3703. """
  3704. self.defaults.report_usage("on_delete()")
  3705. response = None
  3706. bt_ok = None
  3707. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3708. # a geometry object before we update it.
  3709. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3710. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3711. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3712. msgbox = QtWidgets.QMessageBox()
  3713. msgbox.setWindowTitle(_("Delete objects"))
  3714. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3715. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3716. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3717. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3718. "the selected objects?"))
  3719. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3720. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3721. msgbox.setDefaultButton(bt_ok)
  3722. msgbox.exec_()
  3723. response = msgbox.clickedButton()
  3724. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3725. response = bt_ok
  3726. if response == bt_ok:
  3727. if self.collection.get_active():
  3728. self.log.debug("App.on_delete()")
  3729. for obj_active in self.collection.get_selected():
  3730. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3731. if obj_active.kind == 'gerber':
  3732. obj_active.mark_shapes_storage.clear()
  3733. obj_active.mark_shapes.clear(update=True)
  3734. obj_active.mark_shapes.enabled = False
  3735. elif obj_active.kind == 'cncjob':
  3736. try:
  3737. obj_active.text_col.enabled = False
  3738. del obj_active.text_col
  3739. obj_active.annotation.clear(update=True)
  3740. del obj_active.annotation
  3741. obj_active.probing_shapes.clear(update=True)
  3742. except AttributeError as e:
  3743. self.log.debug(
  3744. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3745. )
  3746. while self.collection.get_selected():
  3747. self.delete_first_selected()
  3748. # make sure that the selection shape is deleted, too
  3749. self.delete_selection_shape()
  3750. # if there are no longer objects delete also the exclusion areas shapes
  3751. if not self.collection.get_list():
  3752. self.exc_areas.clear_shapes()
  3753. self.inform.emit('%s...' % _("Object(s) deleted"))
  3754. else:
  3755. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3756. else:
  3757. self.inform.emit(_("Save the work in Editor and try again ..."))
  3758. def delete_first_selected(self):
  3759. # Keep this for later
  3760. try:
  3761. sel_obj = self.collection.get_active()
  3762. name = sel_obj.options["name"]
  3763. isPlotted = sel_obj.options["plot"]
  3764. except AttributeError:
  3765. self.log.debug("Nothing selected for deletion")
  3766. return
  3767. if self.is_legacy is True:
  3768. # Remove plot only if the object was plotted otherwise delaxes will fail
  3769. if isPlotted:
  3770. try:
  3771. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3772. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3773. except Exception as e:
  3774. self.log.debug("App.delete_first_selected() --> %s" % str(e))
  3775. self.plotcanvas.auto_adjust_axes()
  3776. # Remove from dictionary
  3777. self.collection.delete_active()
  3778. # Clear form
  3779. self.setup_default_properties_tab()
  3780. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3781. def on_set_origin(self):
  3782. """
  3783. Set the origin to the left mouse click position
  3784. :return: None
  3785. """
  3786. # display the message for the user
  3787. # and ask him to click on the desired position
  3788. self.defaults.report_usage("on_set_origin()")
  3789. def origin_replot():
  3790. def worker_task():
  3791. with self.proc_container.new('%s...' % _("Plotting")):
  3792. for obj in self.collection.get_list():
  3793. obj.plot()
  3794. self.plotcanvas.fit_view()
  3795. if self.is_legacy:
  3796. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3797. else:
  3798. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3799. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3800. self.inform.emit(_('Click to set the origin ...'))
  3801. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3802. # first disconnect it as it may have been used by something else
  3803. try:
  3804. self.replot_signal.disconnect()
  3805. except TypeError:
  3806. pass
  3807. self.replot_signal[list].connect(origin_replot)
  3808. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3809. """
  3810. :param event:
  3811. :param location:
  3812. :param noplot:
  3813. :param use_thread:
  3814. :return:
  3815. """
  3816. noplot_sig = noplot
  3817. def worker_task():
  3818. with self.proc_container.new(_("Setting Origin...")):
  3819. obj_list = self.collection.get_list()
  3820. for obj in obj_list:
  3821. obj.offset((x, y))
  3822. self.app_obj.object_changed.emit(obj)
  3823. # Update the object bounding box options
  3824. a, b, c, d = obj.bounds()
  3825. obj.options['xmin'] = a
  3826. obj.options['ymin'] = b
  3827. obj.options['xmax'] = c
  3828. obj.options['ymax'] = d
  3829. self.inform.emit('[success] %s...' % _('Origin set'))
  3830. for obj in obj_list:
  3831. out_name = obj.options["name"]
  3832. if obj.kind == 'gerber':
  3833. obj.source_file = self.f_handlers.export_gerber(
  3834. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3835. elif obj.kind == 'excellon':
  3836. obj.source_file = self.f_handlers.export_excellon(
  3837. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3838. if noplot_sig is False:
  3839. self.replot_signal.emit([])
  3840. if location is not None:
  3841. if len(location) != 2:
  3842. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3843. return 'fail'
  3844. x, y = location
  3845. if use_thread is True:
  3846. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3847. else:
  3848. worker_task()
  3849. self.should_we_save = True
  3850. return
  3851. if event is not None and event.button == 1:
  3852. if self.is_legacy is False:
  3853. event_pos = event.pos
  3854. else:
  3855. event_pos = (event.xdata, event.ydata)
  3856. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3857. if self.grid_status():
  3858. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3859. else:
  3860. pos = pos_canvas
  3861. x = 0 - pos[0]
  3862. y = 0 - pos[1]
  3863. if use_thread is True:
  3864. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3865. else:
  3866. worker_task()
  3867. self.should_we_save = True
  3868. def on_move2origin(self, use_thread=True):
  3869. """
  3870. Move selected objects to origin.
  3871. :param use_thread: Control if to use threaded operation. Boolean.
  3872. :return:
  3873. """
  3874. def worker_task():
  3875. with self.proc_container.new(_("Moving to Origin...")):
  3876. obj_list = self.collection.get_selected()
  3877. if not obj_list:
  3878. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3879. return
  3880. xminlist = []
  3881. yminlist = []
  3882. # first get a bounding box to fit all
  3883. for obj in obj_list:
  3884. xmin, ymin, xmax, ymax = obj.bounds()
  3885. xminlist.append(xmin)
  3886. yminlist.append(ymin)
  3887. # get the minimum x,y for all objects selected
  3888. x = min(xminlist)
  3889. y = min(yminlist)
  3890. for obj in obj_list:
  3891. obj.offset((-x, -y))
  3892. self.app_obj.object_changed.emit(obj)
  3893. # Update the object bounding box options
  3894. a, b, c, d = obj.bounds()
  3895. obj.options['xmin'] = a
  3896. obj.options['ymin'] = b
  3897. obj.options['xmax'] = c
  3898. obj.options['ymax'] = d
  3899. for obj in obj_list:
  3900. obj.plot()
  3901. for obj in obj_list:
  3902. out_name = obj.options["name"]
  3903. if obj.kind == 'gerber':
  3904. obj.source_file = self.f_handlers.export_gerber(
  3905. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3906. elif obj.kind == 'excellon':
  3907. obj.source_file = self.f_handlers.export_excellon(
  3908. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3909. self.inform.emit('[success] %s...' % _('Origin set'))
  3910. if use_thread is True:
  3911. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3912. else:
  3913. worker_task()
  3914. self.should_we_save = True
  3915. def on_jump_to(self, custom_location=None, fit_center=True):
  3916. """
  3917. Jump to a location by setting the mouse cursor location.
  3918. :param custom_location: Jump to a specified point. (x, y) tuple.
  3919. :param fit_center: If to fit view. Boolean.
  3920. :return:
  3921. """
  3922. self.defaults.report_usage("on_jump_to()")
  3923. if not custom_location:
  3924. dia_box_location = None
  3925. try:
  3926. dia_box_location = eval(self.clipboard.text())
  3927. except Exception:
  3928. pass
  3929. if type(dia_box_location) == tuple:
  3930. dia_box_location = str(dia_box_location)
  3931. else:
  3932. dia_box_location = None
  3933. # dia_box = Dialog_box(title=_("Jump to ..."),
  3934. # label=_("Enter the coordinates in format X,Y:"),
  3935. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3936. # initial_text=dia_box_location)
  3937. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3938. label=_("Enter the coordinates in format X,Y:"),
  3939. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3940. initial_text=dia_box_location,
  3941. reference=self.defaults['global_jump_ref'])
  3942. if dia_box.ok is True:
  3943. try:
  3944. location = eval(dia_box.location)
  3945. if not isinstance(location, tuple):
  3946. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3947. return
  3948. if dia_box.reference == 'rel':
  3949. rel_x = self.mouse[0] + location[0]
  3950. rel_y = self.mouse[1] + location[1]
  3951. location = (rel_x, rel_y)
  3952. self.defaults['global_jump_ref'] = dia_box.reference
  3953. except Exception:
  3954. return
  3955. else:
  3956. return
  3957. else:
  3958. location = custom_location
  3959. self.jump_signal.emit(location)
  3960. if fit_center:
  3961. self.plotcanvas.fit_center(loc=location)
  3962. cursor = QtGui.QCursor()
  3963. if self.is_legacy is False:
  3964. # I don't know where those differences come from but they are constant for the current
  3965. # execution of the application and they are multiples of a value around 0.0263mm.
  3966. # In a random way sometimes they are more sometimes they are less
  3967. # if units == 'MM':
  3968. # cal_factor = 0.0263
  3969. # else:
  3970. # cal_factor = 0.0263 / 25.4
  3971. cal_location = (location[0], location[1])
  3972. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3973. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3974. j_pos = (
  3975. int(canvas_origin.x() + round(jump_loc[0])),
  3976. int(canvas_origin.y() + round(jump_loc[1]))
  3977. )
  3978. cursor.setPos(j_pos[0], j_pos[1])
  3979. else:
  3980. # find the canvas origin which is in the top left corner
  3981. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3982. # determine the coordinates for the lowest left point of the canvas
  3983. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3984. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3985. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3986. # canvas) and the point (width, height) is in the top-right location
  3987. loc = self.plotcanvas.axes.transData.transform_point(location)
  3988. j_pos = (
  3989. int(x0 + loc[0]),
  3990. int(y0 - loc[1])
  3991. )
  3992. cursor.setPos(j_pos[0], j_pos[1])
  3993. self.plotcanvas.mouse = [location[0], location[1]]
  3994. if self.defaults["global_cursor_color_enabled"] is True:
  3995. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3996. else:
  3997. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3998. if self.grid_status():
  3999. # Update cursor
  4000. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4001. symbol='++', edge_color=self.cursor_color_3D,
  4002. edge_width=self.defaults["global_cursor_width"],
  4003. size=self.defaults["global_cursor_size"])
  4004. # Set the relative position label
  4005. dx = location[0] - float(self.rel_point1[0])
  4006. dy = location[1] - float(self.rel_point1[1])
  4007. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4008. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4009. # Set the position label
  4010. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4011. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4012. units = self.defaults["units"].lower()
  4013. self.plotcanvas.text_hud.text = \
  4014. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4015. dx, units, dy, units, location[0], units, location[1], units)
  4016. self.inform.emit('[success] %s' % _("Done."))
  4017. return location
  4018. def on_locate(self, obj, fit_center=True):
  4019. """
  4020. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4021. :param obj: The object on which to locate certain points
  4022. :param fit_center: If to fit view. Boolean.
  4023. :return: A point location. (x, y) tuple.
  4024. """
  4025. self.defaults.report_usage("on_locate()")
  4026. if obj is None:
  4027. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4028. return 'fail'
  4029. class DialogBoxChoice(QtWidgets.QDialog):
  4030. def __init__(self, title=None, icon=None, choice='bl'):
  4031. """
  4032. :param title: string with the window title
  4033. """
  4034. super(DialogBoxChoice, self).__init__()
  4035. self.ok = False
  4036. self.setWindowIcon(icon)
  4037. self.setWindowTitle(str(title))
  4038. self.form = QtWidgets.QFormLayout(self)
  4039. self.ref_radio = RadioSet([
  4040. {"label": _("Bottom-Left"), "value": "bl"},
  4041. {"label": _("Top-Left"), "value": "tl"},
  4042. {"label": _("Bottom-Right"), "value": "br"},
  4043. {"label": _("Top-Right"), "value": "tr"},
  4044. {"label": _("Center"), "value": "c"}
  4045. ], orientation='vertical', stretch=False)
  4046. self.ref_radio.set_value(choice)
  4047. self.form.addRow(self.ref_radio)
  4048. self.button_box = QtWidgets.QDialogButtonBox(
  4049. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4050. Qt.Horizontal, parent=self)
  4051. self.form.addRow(self.button_box)
  4052. self.button_box.accepted.connect(self.accept)
  4053. self.button_box.rejected.connect(self.reject)
  4054. if self.exec_() == QtWidgets.QDialog.Accepted:
  4055. self.ok = True
  4056. self.location_point = self.ref_radio.get_value()
  4057. else:
  4058. self.ok = False
  4059. self.location_point = None
  4060. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4061. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4062. choice=self.defaults['global_locate_pt'])
  4063. if dia_box.ok is True:
  4064. try:
  4065. location_point = dia_box.location_point
  4066. self.defaults['global_locate_pt'] = dia_box.location_point
  4067. except Exception:
  4068. return
  4069. else:
  4070. return
  4071. loc_b = obj.bounds()
  4072. if location_point == 'bl':
  4073. location = (loc_b[0], loc_b[1])
  4074. elif location_point == 'tl':
  4075. location = (loc_b[0], loc_b[3])
  4076. elif location_point == 'br':
  4077. location = (loc_b[2], loc_b[1])
  4078. elif location_point == 'tr':
  4079. location = (loc_b[2], loc_b[3])
  4080. else:
  4081. # center
  4082. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4083. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4084. location = (cx, cy)
  4085. self.locate_signal.emit(location, location_point)
  4086. if fit_center:
  4087. self.plotcanvas.fit_center(loc=location)
  4088. cursor = QtGui.QCursor()
  4089. if self.is_legacy is False:
  4090. # I don't know where those differences come from but they are constant for the current
  4091. # execution of the application and they are multiples of a value around 0.0263mm.
  4092. # In a random way sometimes they are more sometimes they are less
  4093. # if units == 'MM':
  4094. # cal_factor = 0.0263
  4095. # else:
  4096. # cal_factor = 0.0263 / 25.4
  4097. cal_location = (location[0], location[1])
  4098. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4099. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4100. j_pos = (
  4101. int(canvas_origin.x() + round(jump_loc[0])),
  4102. int(canvas_origin.y() + round(jump_loc[1]))
  4103. )
  4104. cursor.setPos(j_pos[0], j_pos[1])
  4105. else:
  4106. # find the canvas origin which is in the top left corner
  4107. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4108. # determine the coordinates for the lowest left point of the canvas
  4109. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4110. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4111. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4112. # canvas) and the point (width, height) is in the top-right location
  4113. loc = self.plotcanvas.axes.transData.transform_point(location)
  4114. j_pos = (
  4115. int(x0 + loc[0]),
  4116. int(y0 - loc[1])
  4117. )
  4118. cursor.setPos(j_pos[0], j_pos[1])
  4119. self.plotcanvas.mouse = [location[0], location[1]]
  4120. if self.defaults["global_cursor_color_enabled"] is True:
  4121. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4122. else:
  4123. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4124. if self.grid_status():
  4125. # Update cursor
  4126. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4127. symbol='++', edge_color=self.cursor_color_3D,
  4128. edge_width=self.defaults["global_cursor_width"],
  4129. size=self.defaults["global_cursor_size"])
  4130. # Set the relative position label
  4131. self.dx = location[0] - float(self.rel_point1[0])
  4132. self.dy = location[1] - float(self.rel_point1[1])
  4133. # Set the position label
  4134. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4135. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4136. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4137. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4138. units = self.defaults["units"].lower()
  4139. self.plotcanvas.text_hud.text = \
  4140. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4141. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4142. self.inform.emit('[success] %s' % _("Done."))
  4143. return location
  4144. def on_copy_command(self):
  4145. """
  4146. Will copy a selection of objects, creating new objects.
  4147. :return:
  4148. """
  4149. self.defaults.report_usage("on_copy_command()")
  4150. def initialize(obj_init, app_obj):
  4151. """
  4152. :param obj_init: the new object
  4153. :type obj_init: class
  4154. :param app_obj: An instance of the App class
  4155. :type app_obj: App
  4156. :return: None
  4157. :rtype:
  4158. """
  4159. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4160. try:
  4161. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4162. except AttributeError:
  4163. pass
  4164. try:
  4165. obj_init.apertures = deepcopy(obj.apertures)
  4166. except AttributeError:
  4167. pass
  4168. try:
  4169. if obj.tools:
  4170. obj_init.tools = deepcopy(obj.tools)
  4171. except Exception as err:
  4172. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4173. try:
  4174. obj_init.source_file = deepcopy(obj.source_file)
  4175. except (AttributeError, TypeError):
  4176. pass
  4177. def initialize_excellon(obj_init, app_obj):
  4178. obj_init.source_file = deepcopy(obj.source_file)
  4179. obj_init.tools = deepcopy(obj.tools)
  4180. # drills are offset, so they need to be deep copied
  4181. obj_init.drills = deepcopy(obj.drills)
  4182. # slots are offset, so they need to be deep copied
  4183. obj_init.slots = deepcopy(obj.slots)
  4184. obj_init.create_geometry()
  4185. if not obj_init.tools:
  4186. app_obj.debug("on_copy_command() --> no excellon tools")
  4187. return 'fail'
  4188. def initialize_script(obj_init, app_obj):
  4189. obj_init.source_file = deepcopy(obj.source_file)
  4190. def initialize_document(obj_init, app_obj):
  4191. obj_init.source_file = deepcopy(obj.source_file)
  4192. for obj in self.collection.get_selected():
  4193. obj_name = obj.options["name"]
  4194. try:
  4195. if isinstance(obj, ExcellonObject):
  4196. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4197. elif isinstance(obj, GerberObject):
  4198. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4199. elif isinstance(obj, GeometryObject):
  4200. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4201. elif isinstance(obj, ScriptObject):
  4202. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4203. elif isinstance(obj, DocumentObject):
  4204. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4205. except Exception as e:
  4206. return "Operation failed: %s" % str(e)
  4207. def on_copy_object2(self, custom_name):
  4208. def initialize_geometry(obj_init, app_obj):
  4209. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4210. try:
  4211. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4212. except AttributeError:
  4213. pass
  4214. try:
  4215. obj_init.apertures = deepcopy(obj.apertures)
  4216. except AttributeError:
  4217. pass
  4218. try:
  4219. if obj.tools:
  4220. obj_init.tools = deepcopy(obj.tools)
  4221. except Exception as ee:
  4222. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4223. def initialize_gerber(obj_init, app_obj):
  4224. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4225. obj_init.apertures = deepcopy(obj.apertures)
  4226. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4227. if not obj_init.apertures:
  4228. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4229. return 'fail'
  4230. def initialize_excellon(obj_init, app_obj):
  4231. obj_init.tools = deepcopy(obj.tools)
  4232. # drills are offset, so they need to be deep copied
  4233. obj_init.drills = deepcopy(obj.drills)
  4234. # slots are offset, so they need to be deep copied
  4235. obj_init.slots = deepcopy(obj.slots)
  4236. obj_init.create_geometry()
  4237. if not obj_init.tools:
  4238. app_obj.debug("on_copy_object2() --> no excellon tools")
  4239. return 'fail'
  4240. for obj in self.collection.get_selected():
  4241. obj_name = obj.options["name"]
  4242. try:
  4243. if isinstance(obj, ExcellonObject):
  4244. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4245. elif isinstance(obj, GerberObject):
  4246. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4247. elif isinstance(obj, GeometryObject):
  4248. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4249. except Exception as er:
  4250. return "Operation failed: %s" % str(er)
  4251. def on_rename_object(self, text):
  4252. """
  4253. Will rename an object.
  4254. :param text: New name for the object.
  4255. :return:
  4256. """
  4257. self.defaults.report_usage("on_rename_object()")
  4258. named_obj = self.collection.get_active()
  4259. for obj in named_obj:
  4260. if obj is list:
  4261. self.on_rename_object(text)
  4262. else:
  4263. try:
  4264. obj.options['name'] = text
  4265. except Exception as e:
  4266. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4267. def convert_any2geo(self):
  4268. """
  4269. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4270. :return:
  4271. """
  4272. self.defaults.report_usage("convert_any2geo()")
  4273. def initialize(obj_init, app):
  4274. obj_init.solid_geometry = obj.solid_geometry
  4275. try:
  4276. obj_init.follow_geometry = obj.follow_geometry
  4277. except AttributeError:
  4278. pass
  4279. try:
  4280. obj_init.apertures = obj.apertures
  4281. except AttributeError:
  4282. pass
  4283. try:
  4284. if obj.tools:
  4285. obj_init.tools = obj.tools
  4286. except AttributeError:
  4287. pass
  4288. def initialize_excellon(obj_init, app_obj):
  4289. # objs = self.collection.get_selected()
  4290. # GeometryObject.merge(objs, obj)
  4291. solid_geo = []
  4292. for tool in obj.tools:
  4293. for geo in obj.tools[tool]['solid_geometry']:
  4294. solid_geo.append(geo)
  4295. obj_init.solid_geometry = deepcopy(solid_geo)
  4296. if not obj_init.solid_geometry:
  4297. app_obj.log("convert_any2geo() failed")
  4298. return 'fail'
  4299. if not self.collection.get_selected():
  4300. log.warning("App.convert_any2geo --> No object selected")
  4301. self.inform.emit('[WARNING_NOTCL] %s' %
  4302. _("No object is selected. Select an object and try again."))
  4303. return
  4304. for obj in self.collection.get_selected():
  4305. obj_name = obj.options["name"]
  4306. try:
  4307. if obj.kind == 'excellon':
  4308. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4309. else:
  4310. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4311. except Exception as e:
  4312. return "Operation failed: %s" % str(e)
  4313. def convert_any2gerber(self):
  4314. """
  4315. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4316. :return:
  4317. """
  4318. def initialize_geometry(obj_init, app_obj):
  4319. apertures = {}
  4320. apid = 0
  4321. apertures[str(apid)] = {}
  4322. apertures[str(apid)]['geometry'] = []
  4323. for obj_orig in obj.solid_geometry:
  4324. new_elem = {}
  4325. new_elem['solid'] = obj_orig
  4326. try:
  4327. new_elem['follow'] = obj_orig.exterior
  4328. except AttributeError:
  4329. pass
  4330. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4331. apertures[str(apid)]['size'] = 0.0
  4332. apertures[str(apid)]['type'] = 'C'
  4333. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4334. obj_init.apertures = deepcopy(apertures)
  4335. if not obj_init.apertures:
  4336. app_obj.log("convert_any2gerber() failed")
  4337. return 'fail'
  4338. def initialize_excellon(obj_init, app_obj):
  4339. apertures = {}
  4340. apid = 10
  4341. for tool in obj.tools:
  4342. apertures[str(apid)] = {}
  4343. apertures[str(apid)]['geometry'] = []
  4344. for geo in obj.tools[tool]['solid_geometry']:
  4345. new_el = {}
  4346. new_el['solid'] = geo
  4347. new_el['follow'] = geo.exterior
  4348. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4349. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4350. apertures[str(apid)]['type'] = 'C'
  4351. apid += 1
  4352. # create solid_geometry
  4353. solid_geometry = []
  4354. for apid in apertures:
  4355. for geo_el in apertures[apid]['geometry']:
  4356. solid_geometry.append(geo_el['solid'])
  4357. solid_geometry = MultiPolygon(solid_geometry)
  4358. solid_geometry = solid_geometry.buffer(0.0000001)
  4359. obj_init.solid_geometry = deepcopy(solid_geometry)
  4360. obj_init.apertures = deepcopy(apertures)
  4361. if not obj_init.apertures:
  4362. app_obj.log("convert_any2gerber() failed")
  4363. return 'fail'
  4364. if not self.collection.get_selected():
  4365. log.warning("App.convert_any2gerber --> No object selected")
  4366. self.inform.emit('[WARNING_NOTCL] %s' %
  4367. _("No object is selected. Select an object and try again."))
  4368. return
  4369. for obj in self.collection.get_selected():
  4370. obj_name = obj.options["name"]
  4371. try:
  4372. if obj.kind == 'excellon':
  4373. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4374. elif obj.kind == 'geometry':
  4375. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4376. else:
  4377. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4378. except Exception as e:
  4379. return "Operation failed: %s" % str(e)
  4380. def convert_any2excellon(self):
  4381. """
  4382. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4383. :return:
  4384. """
  4385. def initialize_geometry(obj_init, app_obj):
  4386. tools = {}
  4387. tooluid = 1
  4388. obj_init.solid_geometry = []
  4389. for geo in obj.solid_geometry:
  4390. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4391. continue
  4392. minx, miny, maxx, maxy = geo.bounds
  4393. new_dia = min([maxx-minx, maxy-miny])
  4394. new_drill = geo.centroid
  4395. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4396. current_tooldias = []
  4397. if tools:
  4398. for tool in tools:
  4399. if tools[tool] and 'tooldia' in tools[tool]:
  4400. current_tooldias.append(tools[tool]['tooldia'])
  4401. if new_dia in current_tooldias:
  4402. digits = app_obj.decimals
  4403. for tool in tools:
  4404. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4405. tools[tool]['drills'].append(new_drill)
  4406. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4407. else:
  4408. tools[tooluid] = {}
  4409. tools[tooluid]['tooldia'] = new_dia
  4410. tools[tooluid]['drills'] = [new_drill]
  4411. tools[tooluid]['slots'] = []
  4412. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4413. tooluid += 1
  4414. try:
  4415. obj_init.solid_geometry.append(new_drill_geo)
  4416. except (TypeError, AttributeError):
  4417. obj_init.solid_geometry = [new_drill_geo]
  4418. obj_init.tools = deepcopy(tools)
  4419. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4420. if not obj_init.solid_geometry:
  4421. return 'fail'
  4422. def initialize_gerber(obj_init, app_obj):
  4423. tools = {}
  4424. tooluid = 1
  4425. digits = app_obj.decimals
  4426. obj_init.solid_geometry = []
  4427. for apid in obj.apertures:
  4428. if 'geometry' in obj.apertures[apid]:
  4429. for geo_dict in obj.apertures[apid]['geometry']:
  4430. if 'follow' in geo_dict:
  4431. if isinstance(geo_dict['follow'], Point):
  4432. geo = geo_dict['solid']
  4433. minx, miny, maxx, maxy = geo.bounds
  4434. new_dia = min([maxx - minx, maxy - miny])
  4435. new_drill = geo.centroid
  4436. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4437. current_tooldias = []
  4438. if tools:
  4439. for tool in tools:
  4440. if tools[tool] and 'tooldia' in tools[tool]:
  4441. current_tooldias.append(
  4442. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4443. )
  4444. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4445. if formatted_new_dia in current_tooldias:
  4446. for tool in tools:
  4447. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4448. if new_drill not in tools[tool]['drills']:
  4449. tools[tool]['drills'].append(new_drill)
  4450. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4451. else:
  4452. tools[tooluid] = {}
  4453. tools[tooluid]['tooldia'] = new_dia
  4454. tools[tooluid]['drills'] = [new_drill]
  4455. tools[tooluid]['slots'] = []
  4456. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4457. tooluid += 1
  4458. try:
  4459. obj_init.solid_geometry.append(new_drill_geo)
  4460. except (TypeError, AttributeError):
  4461. obj_init.solid_geometry = [new_drill_geo]
  4462. elif isinstance(geo_dict['follow'], LineString):
  4463. geo_coords = list(geo_dict['follow'].coords)
  4464. # slots can have only a start and stop point and no intermediate points
  4465. if len(geo_coords) != 2:
  4466. continue
  4467. geo = geo_dict['solid']
  4468. try:
  4469. new_dia = obj.apertures[apid]['size']
  4470. except Exception:
  4471. continue
  4472. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4473. new_slot_geo = geo
  4474. current_tooldias = []
  4475. if tools:
  4476. for tool in tools:
  4477. if tools[tool] and 'tooldia' in tools[tool]:
  4478. current_tooldias.append(
  4479. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4480. )
  4481. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4482. for tool in tools:
  4483. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4484. '%.*f' % (self.decimals, new_dia)):
  4485. if new_slot not in tools[tool]['slots']:
  4486. tools[tool]['slots'].append(new_slot)
  4487. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4488. else:
  4489. tools[tooluid] = {}
  4490. tools[tooluid]['tooldia'] = new_dia
  4491. tools[tooluid]['drills'] = []
  4492. tools[tooluid]['slots'] = [new_slot]
  4493. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4494. tooluid += 1
  4495. try:
  4496. obj_init.solid_geometry.append(new_slot_geo)
  4497. except (TypeError, AttributeError):
  4498. obj_init.solid_geometry = [new_slot_geo]
  4499. obj_init.tools = deepcopy(tools)
  4500. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4501. if not obj_init.solid_geometry:
  4502. return 'fail'
  4503. if not self.collection.get_selected():
  4504. log.warning("App.convert_any2excellon--> No object selected")
  4505. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4506. return
  4507. for obj in self.collection.get_selected():
  4508. obj_name = obj.options["name"]
  4509. try:
  4510. if obj.kind == 'gerber':
  4511. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4512. elif obj.kind == 'geometry':
  4513. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4514. else:
  4515. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4516. except Exception as e:
  4517. return "Operation failed: %s" % str(e)
  4518. def abort_all_tasks(self):
  4519. """
  4520. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4521. on the first possible occasion.
  4522. :return:
  4523. """
  4524. if self.abort_flag is False:
  4525. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4526. self.abort_flag = True
  4527. self.cleanup.emit()
  4528. def app_is_idle(self):
  4529. if self.abort_flag:
  4530. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4531. self.abort_flag = False
  4532. def on_selectall(self):
  4533. """
  4534. Will draw a selection box shape around the selected objects.
  4535. :return:
  4536. """
  4537. self.defaults.report_usage("on_selectall()")
  4538. # delete the possible selection box around a possible selected object
  4539. self.delete_selection_shape()
  4540. for name in self.collection.get_names():
  4541. self.collection.set_active(name)
  4542. curr_sel_obj = self.collection.get_by_name(name)
  4543. # create the selection box around the selected object
  4544. if self.defaults['global_selection_shape'] is True:
  4545. self.draw_selection_shape(curr_sel_obj)
  4546. def on_toggle_preferences(self):
  4547. pref_open = False
  4548. for idx in range(self.ui.plot_tab_area.count()):
  4549. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4550. pref_open = True
  4551. if pref_open:
  4552. for idx in range(self.ui.plot_tab_area.count()):
  4553. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4554. self.ui.plot_tab_area.removeTab(idx)
  4555. break
  4556. self.ui.pref_status_label.setStyleSheet("")
  4557. else:
  4558. self.on_preferences()
  4559. def on_preferences(self):
  4560. """
  4561. Adds the Preferences in a Tab in Plot Area
  4562. :return:
  4563. """
  4564. # add the tab if it was closed
  4565. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4566. # delete the absolute and relative position and messages in the infobar
  4567. # self.ui.position_label.setText("")
  4568. # self.ui.rel_position_label.setText("")
  4569. # hide coordinates toolbars in the infobar while in DB
  4570. self.ui.coords_toolbar.hide()
  4571. self.ui.delta_coords_toolbar.hide()
  4572. # Switch plot_area to preferences page
  4573. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4574. # self.ui.show()
  4575. self.ui.pref_status_label.setStyleSheet("""
  4576. QLabel
  4577. {
  4578. color: black;
  4579. background-color: lightseagreen;
  4580. }
  4581. """
  4582. )
  4583. # detect changes in the preferences
  4584. for idx in range(self.ui.pref_tab_area.count()):
  4585. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4586. try:
  4587. try:
  4588. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4589. except (TypeError, AttributeError):
  4590. pass
  4591. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4592. except AttributeError:
  4593. pass
  4594. try:
  4595. try:
  4596. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4597. except (TypeError, AttributeError):
  4598. pass
  4599. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4600. except AttributeError:
  4601. pass
  4602. try:
  4603. try:
  4604. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4605. except (TypeError, AttributeError):
  4606. pass
  4607. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4608. except AttributeError:
  4609. pass
  4610. try:
  4611. try:
  4612. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4613. except (TypeError, AttributeError):
  4614. pass
  4615. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4616. except AttributeError:
  4617. pass
  4618. try:
  4619. try:
  4620. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4621. except (TypeError, AttributeError):
  4622. pass
  4623. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4624. except AttributeError:
  4625. pass
  4626. def on_tools_database(self, source='app'):
  4627. """
  4628. Adds the Tools Database in a Tab in Plot Area.
  4629. :return:
  4630. """
  4631. filename = self.tools_database_path()
  4632. # load the database tools from the file
  4633. try:
  4634. with open(filename) as f:
  4635. __ = f.read()
  4636. except Exception as eros:
  4637. self.log.debug("The tools DB file is not loaded: %s" % str(eros))
  4638. log.error("Could not access tools DB file. The file may be locked,\n"
  4639. "not existing or doesn't have the read permissions.\n"
  4640. "Check to see if exists, it should be here: %s\n"
  4641. "It may help to reboot the app, it will try to recreate it if it's missing." % self.data_path)
  4642. self.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  4643. return 'fail'
  4644. for idx in range(self.ui.plot_tab_area.count()):
  4645. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4646. # there can be only one instance of Tools Database at one time
  4647. return
  4648. if source == 'app':
  4649. self.tools_db_tab = ToolsDB2(
  4650. app=self,
  4651. parent=self.ui,
  4652. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4653. )
  4654. elif source == 'ncc':
  4655. self.tools_db_tab = ToolsDB2(
  4656. app=self,
  4657. parent=self.ui,
  4658. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4659. )
  4660. elif source == 'paint':
  4661. self.tools_db_tab = ToolsDB2(
  4662. app=self,
  4663. parent=self.ui,
  4664. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4665. )
  4666. elif source == 'iso':
  4667. self.tools_db_tab = ToolsDB2(
  4668. app=self,
  4669. parent=self.ui,
  4670. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4671. )
  4672. elif source == 'cutout':
  4673. self.tools_db_tab = ToolsDB2(
  4674. app=self,
  4675. parent=self.ui,
  4676. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4677. )
  4678. # add the tab if it was closed
  4679. try:
  4680. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4681. self.tools_db_tab.setObjectName("database_tab")
  4682. except Exception as e:
  4683. self.log.debug("App.on_tools_database() --> %s" % str(e))
  4684. return
  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.tools_db_tab)
  4693. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4694. self.tools_db_tab.ui_connect()
  4695. def on_geometry_tool_add_from_db_executed(self, tool):
  4696. """
  4697. Here add the tool from DB in the selected geometry object.
  4698. :return:
  4699. """
  4700. tool_from_db = deepcopy(tool)
  4701. obj = self.collection.get_active()
  4702. if obj.kind == 'geometry':
  4703. if tool['data']['tool_target'] not in [0, 1]: # General, Milling Type
  4704. # close the tab and delete it
  4705. for idx in range(self.ui.plot_tab_area.count()):
  4706. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4707. wdg = self.ui.plot_tab_area.widget(idx)
  4708. wdg.deleteLater()
  4709. self.ui.plot_tab_area.removeTab(idx)
  4710. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4711. return
  4712. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4713. # close the tab and delete it
  4714. for idx in range(self.ui.plot_tab_area.count()):
  4715. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4716. wdg = self.ui.plot_tab_area.widget(idx)
  4717. wdg.deleteLater()
  4718. self.ui.plot_tab_area.removeTab(idx)
  4719. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4720. elif obj.kind == 'gerber':
  4721. if tool['data']['tool_target'] not in [0, 3]: # General, Isolation Type
  4722. # close the tab and delete it
  4723. for idx in range(self.ui.plot_tab_area.count()):
  4724. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4725. wdg = self.ui.plot_tab_area.widget(idx)
  4726. wdg.deleteLater()
  4727. self.ui.plot_tab_area.removeTab(idx)
  4728. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4729. return
  4730. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4731. # close the tab and delete it
  4732. for idx in range(self.ui.plot_tab_area.count()):
  4733. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4734. wdg = self.ui.plot_tab_area.widget(idx)
  4735. wdg.deleteLater()
  4736. self.ui.plot_tab_area.removeTab(idx)
  4737. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4738. else:
  4739. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4740. def on_plot_area_tab_closed(self, tab_obj_name):
  4741. """
  4742. Executed whenever a QTab is closed in the Plot Area.
  4743. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4744. :return:
  4745. """
  4746. if tab_obj_name == "preferences_tab":
  4747. self.preferencesUiManager.on_close_preferences_tab()
  4748. elif tab_obj_name == "database_tab":
  4749. # disconnect the signals from the table widget in tab
  4750. self.tools_db_tab.ui_disconnect()
  4751. if self.tools_db_changed_flag is True:
  4752. msgbox = QtWidgets.QMessageBox()
  4753. msgbox.setText(_("One or more Tools are edited.\n"
  4754. "Do you want to update the Tools Database?"))
  4755. msgbox.setWindowTitle(_("Save Tools Database"))
  4756. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4757. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4758. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4759. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4760. msgbox.setDefaultButton(bt_yes)
  4761. msgbox.exec_()
  4762. response = msgbox.clickedButton()
  4763. if response == bt_yes:
  4764. self.tools_db_tab.on_save_tools_db()
  4765. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4766. else:
  4767. self.tools_db_changed_flag = False
  4768. self.inform.emit('')
  4769. return
  4770. self.tools_db_tab.deleteLater()
  4771. elif tab_obj_name == "text_editor_tab":
  4772. self.toggle_codeeditor = False
  4773. elif tab_obj_name == "bookmarks_tab":
  4774. self.book_dialog_tab.rebuild_actions()
  4775. self.book_dialog_tab.deleteLater()
  4776. else:
  4777. pass
  4778. # restore the coords toolbars
  4779. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4780. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4781. def on_flipy(self):
  4782. """
  4783. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4784. :return:
  4785. """
  4786. self.defaults.report_usage("on_flipy()")
  4787. obj_list = self.collection.get_selected()
  4788. xminlist = []
  4789. yminlist = []
  4790. xmaxlist = []
  4791. ymaxlist = []
  4792. if not obj_list:
  4793. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4794. else:
  4795. try:
  4796. # first get a bounding box to fit all
  4797. for obj in obj_list:
  4798. xmin, ymin, xmax, ymax = obj.bounds()
  4799. xminlist.append(xmin)
  4800. yminlist.append(ymin)
  4801. xmaxlist.append(xmax)
  4802. ymaxlist.append(ymax)
  4803. # get the minimum x,y and maximum x,y for all objects selected
  4804. xminimal = min(xminlist)
  4805. yminimal = min(yminlist)
  4806. xmaximal = max(xmaxlist)
  4807. ymaximal = max(ymaxlist)
  4808. px = 0.5 * (xminimal + xmaximal)
  4809. py = 0.5 * (yminimal + ymaximal)
  4810. # execute mirroring
  4811. for obj in obj_list:
  4812. obj.mirror('X', [px, py])
  4813. obj.plot()
  4814. self.app_obj.object_changed.emit(obj)
  4815. self.inform.emit('[success] %s' %
  4816. _("Flip on Y axis done."))
  4817. except Exception as e:
  4818. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4819. return
  4820. def on_flipx(self):
  4821. """
  4822. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4823. :return:
  4824. """
  4825. self.defaults.report_usage("on_flipx()")
  4826. obj_list = self.collection.get_selected()
  4827. xminlist = []
  4828. yminlist = []
  4829. xmaxlist = []
  4830. ymaxlist = []
  4831. if not obj_list:
  4832. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on X axis."))
  4833. else:
  4834. try:
  4835. # first get a bounding box to fit all
  4836. for obj in obj_list:
  4837. xmin, ymin, xmax, ymax = obj.bounds()
  4838. xminlist.append(xmin)
  4839. yminlist.append(ymin)
  4840. xmaxlist.append(xmax)
  4841. ymaxlist.append(ymax)
  4842. # get the minimum x,y and maximum x,y for all objects selected
  4843. xminimal = min(xminlist)
  4844. yminimal = min(yminlist)
  4845. xmaximal = max(xmaxlist)
  4846. ymaximal = max(ymaxlist)
  4847. px = 0.5 * (xminimal + xmaximal)
  4848. py = 0.5 * (yminimal + ymaximal)
  4849. # execute mirroring
  4850. for obj in obj_list:
  4851. obj.mirror('Y', [px, py])
  4852. obj.plot()
  4853. self.app_obj.object_changed.emit(obj)
  4854. self.inform.emit('[success] %s' %
  4855. _("Flip on X axis done."))
  4856. except Exception as e:
  4857. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4858. return
  4859. def on_rotate(self, silent=False, preset=None):
  4860. """
  4861. Executed when Options -> Rotate Selection menu entry is clicked.
  4862. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4863. :param preset: A value to be used as predefined angle for rotation.
  4864. :return:
  4865. """
  4866. self.defaults.report_usage("on_rotate()")
  4867. obj_list = self.collection.get_selected()
  4868. xminlist = []
  4869. yminlist = []
  4870. xmaxlist = []
  4871. ymaxlist = []
  4872. if not obj_list:
  4873. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4874. else:
  4875. if silent is False:
  4876. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4877. min=-360, max=360, decimals=4,
  4878. init_val=float(self.defaults['tools_transform_rotate']))
  4879. num, ok = rotatebox.get_value()
  4880. else:
  4881. num = preset
  4882. ok = True
  4883. if ok:
  4884. try:
  4885. # first get a bounding box to fit all
  4886. for obj in obj_list:
  4887. xmin, ymin, xmax, ymax = obj.bounds()
  4888. xminlist.append(xmin)
  4889. yminlist.append(ymin)
  4890. xmaxlist.append(xmax)
  4891. ymaxlist.append(ymax)
  4892. # get the minimum x,y and maximum x,y for all objects selected
  4893. xminimal = min(xminlist)
  4894. yminimal = min(yminlist)
  4895. xmaximal = max(xmaxlist)
  4896. ymaximal = max(ymaxlist)
  4897. px = 0.5 * (xminimal + xmaximal)
  4898. py = 0.5 * (yminimal + ymaximal)
  4899. for sel_obj in obj_list:
  4900. sel_obj.rotate(-float(num), point=(px, py))
  4901. sel_obj.plot()
  4902. self.app_obj.object_changed.emit(sel_obj)
  4903. self.inform.emit('[success] %s' % _("Rotation done."))
  4904. except Exception as e:
  4905. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4906. return
  4907. def on_skewx(self):
  4908. """
  4909. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4910. :return:
  4911. """
  4912. self.defaults.report_usage("on_skewx()")
  4913. obj_list = self.collection.get_selected()
  4914. xminlist = []
  4915. yminlist = []
  4916. if not obj_list:
  4917. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4918. else:
  4919. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4920. min=-360, max=360, decimals=4,
  4921. init_val=float(self.defaults['tools_transform_skew_x']))
  4922. num, ok = skewxbox.get_value()
  4923. if ok:
  4924. # first get a bounding box to fit all
  4925. for obj in obj_list:
  4926. xmin, ymin, xmax, ymax = obj.bounds()
  4927. xminlist.append(xmin)
  4928. yminlist.append(ymin)
  4929. # get the minimum x,y and maximum x,y for all objects selected
  4930. xminimal = min(xminlist)
  4931. yminimal = min(yminlist)
  4932. for obj in obj_list:
  4933. obj.skew(num, 0, point=(xminimal, yminimal))
  4934. obj.plot()
  4935. self.app_obj.object_changed.emit(obj)
  4936. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4937. def on_skewy(self):
  4938. """
  4939. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4940. :return:
  4941. """
  4942. self.defaults.report_usage("on_skewy()")
  4943. obj_list = self.collection.get_selected()
  4944. xminlist = []
  4945. yminlist = []
  4946. if not obj_list:
  4947. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4948. else:
  4949. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4950. min=-360, max=360, decimals=4,
  4951. init_val=float(self.defaults['tools_transform_skew_y']))
  4952. num, ok = skewybox.get_value()
  4953. if ok:
  4954. # first get a bounding box to fit all
  4955. for obj in obj_list:
  4956. xmin, ymin, xmax, ymax = obj.bounds()
  4957. xminlist.append(xmin)
  4958. yminlist.append(ymin)
  4959. # get the minimum x,y and maximum x,y for all objects selected
  4960. xminimal = min(xminlist)
  4961. yminimal = min(yminlist)
  4962. for obj in obj_list:
  4963. obj.skew(0, num, point=(xminimal, yminimal))
  4964. obj.plot()
  4965. self.app_obj.object_changed.emit(obj)
  4966. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4967. def on_plots_updated(self):
  4968. """
  4969. Callback used to report when the plots have changed.
  4970. Adjust axes and zooms to fit.
  4971. :return: None
  4972. """
  4973. if self.is_legacy is False:
  4974. self.plotcanvas.update()
  4975. else:
  4976. self.plotcanvas.auto_adjust_axes()
  4977. self.on_zoom_fit()
  4978. self.collection.update_view()
  4979. # self.inform.emit(_("Plots updated ..."))
  4980. def on_toolbar_replot(self):
  4981. """
  4982. Callback for toolbar button. Re-plots all objects.
  4983. :return: None
  4984. """
  4985. self.log.debug("on_toolbar_replot()")
  4986. try:
  4987. obj = self.collection.get_active()
  4988. if obj:
  4989. obj.read_form()
  4990. else:
  4991. self.on_zoom_fit()
  4992. except AttributeError as e:
  4993. self.log.debug("on_toolbar_replot() -> %s" % str(e))
  4994. pass
  4995. self.plot_all()
  4996. def grid_status(self):
  4997. return True if self.ui.grid_snap_btn.isChecked() else False
  4998. def populate_cmenu_grids(self):
  4999. units = self.defaults['units'].lower()
  5000. # for act in self.ui.cmenu_gridmenu.actions():
  5001. # act.triggered.disconnect()
  5002. self.ui.cmenu_gridmenu.clear()
  5003. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5004. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5005. _("Grid On/Off"))
  5006. grid_toggle.setCheckable(True)
  5007. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5008. self.ui.cmenu_gridmenu.addSeparator()
  5009. for grid in sorted_list:
  5010. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5011. "%s" % str(grid))
  5012. action.triggered.connect(self.set_grid)
  5013. self.ui.cmenu_gridmenu.addSeparator()
  5014. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5015. _("Add"))
  5016. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5017. _("Delete"))
  5018. grid_add.triggered.connect(self.on_grid_add)
  5019. grid_delete.triggered.connect(self.on_grid_delete)
  5020. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5021. def set_grid(self):
  5022. menu_action = self.sender()
  5023. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5024. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5025. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5026. def on_grid_add(self):
  5027. # ## Current application units in lower Case
  5028. units = self.defaults['units'].lower()
  5029. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5030. text=_('Enter a Grid Value:'),
  5031. min=0.0000, max=99.9999, decimals=4)
  5032. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5033. val, ok = grid_add_popup.get_value()
  5034. if ok:
  5035. if float(val) == 0:
  5036. self.inform.emit('[WARNING_NOTCL] %s' %
  5037. _("Please enter a grid value with non-zero value, in Float format."))
  5038. return
  5039. else:
  5040. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5041. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5042. self.inform.emit('[success] %s...' % _("New Grid added"))
  5043. else:
  5044. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5045. else:
  5046. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5047. def on_grid_delete(self):
  5048. # ## Current application units in lower Case
  5049. units = self.defaults['units'].lower()
  5050. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5051. text='Enter a Grid Value:',
  5052. min=0.0000, max=99.9999, decimals=4)
  5053. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5054. val, ok = grid_del_popup.get_value()
  5055. if ok:
  5056. if float(val) == 0:
  5057. self.inform.emit('[WARNING_NOTCL] %s' %
  5058. _("Please enter a grid value with non-zero value, in Float format."))
  5059. return
  5060. else:
  5061. try:
  5062. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5063. except ValueError:
  5064. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5065. return
  5066. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5067. else:
  5068. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5069. def on_shortcut_list(self):
  5070. self.defaults.report_usage("on_shortcut_list()")
  5071. # add the tab if it was closed
  5072. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5073. # delete the absolute and relative position and messages in the infobar
  5074. # self.ui.position_label.setText("")
  5075. # self.ui.rel_position_label.setText("")
  5076. # hide coordinates toolbars in the infobar while in DB
  5077. self.ui.coords_toolbar.hide()
  5078. self.ui.delta_coords_toolbar.hide()
  5079. # Switch plot_area to preferences page
  5080. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5081. # self.ui.show()
  5082. def on_select_tab(self, name):
  5083. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5084. if self.ui.splitter.sizes()[0] == 0:
  5085. self.ui.splitter.setSizes([1, 1])
  5086. else:
  5087. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5088. self.ui.splitter.setSizes([0, 1])
  5089. if name == 'project':
  5090. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5091. elif name == 'properties':
  5092. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5093. elif name == 'tool':
  5094. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5095. def on_copy_name(self):
  5096. self.defaults.report_usage("on_copy_name()")
  5097. obj = self.collection.get_active()
  5098. try:
  5099. name = obj.options["name"]
  5100. except AttributeError:
  5101. self.log.debug("on_copy_name() --> No object selected to copy it's name")
  5102. self.inform.emit('[WARNING_NOTCL] %s' %
  5103. _(" No object selected to copy it's name"))
  5104. return
  5105. self.clipboard.setText(name)
  5106. self.inform.emit(_("Name copied on clipboard ..."))
  5107. def on_mouse_click_over_plot(self, event):
  5108. """
  5109. Default actions are:
  5110. :param event: Contains information about the event, like which button
  5111. was clicked, the pixel coordinates and the axes coordinates.
  5112. :return: None
  5113. """
  5114. self.pos = []
  5115. if self.is_legacy is False:
  5116. event_pos = event.pos
  5117. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5118. # # Set the mouse button for panning
  5119. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5120. else:
  5121. event_pos = (event.xdata, event.ydata)
  5122. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5123. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5124. # So it can receive key presses
  5125. self.plotcanvas.native.setFocus()
  5126. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5127. if self.grid_status():
  5128. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5129. else:
  5130. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5131. try:
  5132. if event.button == 1:
  5133. # Reset here the relative coordinates so there is a new reference on the click position
  5134. if self.rel_point1 is None:
  5135. self.rel_point1 = self.pos
  5136. else:
  5137. self.rel_point2 = copy(self.rel_point1)
  5138. self.rel_point1 = self.pos
  5139. self.on_mouse_move_over_plot(event, origin_click=True)
  5140. except Exception as e:
  5141. self.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5142. def on_mouse_double_click_over_plot(self, event):
  5143. if event.button == 1:
  5144. self.doubleclick = True
  5145. def on_mouse_move_over_plot(self, event, origin_click=None):
  5146. """
  5147. Callback for the mouse motion event over the plot.
  5148. :param event: Contains information about the event.
  5149. :param origin_click
  5150. :return: None
  5151. """
  5152. if self.is_legacy is False:
  5153. event_pos = event.pos
  5154. if self.defaults["global_pan_button"] == '2':
  5155. pan_button = 2
  5156. else:
  5157. pan_button = 3
  5158. self.event_is_dragging = event.is_dragging
  5159. else:
  5160. event_pos = (event.xdata, event.ydata)
  5161. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5162. if self.defaults["global_pan_button"] == '2':
  5163. pan_button = 3
  5164. else:
  5165. pan_button = 2
  5166. self.event_is_dragging = self.plotcanvas.is_dragging
  5167. # So it can receive key presses but not when the Tcl Shell is active
  5168. if not self.ui.shell_dock.isVisible():
  5169. if not self.plotcanvas.native.hasFocus():
  5170. self.plotcanvas.native.setFocus()
  5171. self.pos_jump = event_pos
  5172. self.ui.popMenu.mouse_is_panning = False
  5173. if origin_click is None:
  5174. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5175. if event.button == pan_button and self.event_is_dragging == 1:
  5176. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5177. if self.ui.popMenu.popup_active:
  5178. self.ui.popMenu.popup_active = False
  5179. return
  5180. self.ui.popMenu.mouse_is_panning = True
  5181. return
  5182. if self.rel_point1 is not None:
  5183. try: # May fail in case mouse not within axes
  5184. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5185. if pos_canvas[0] is None or pos_canvas[1] is None:
  5186. return
  5187. if self.grid_status():
  5188. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5189. # Update cursor
  5190. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5191. symbol='++', edge_color=self.cursor_color_3D,
  5192. edge_width=self.defaults["global_cursor_width"],
  5193. size=self.defaults["global_cursor_size"])
  5194. else:
  5195. pos = (pos_canvas[0], pos_canvas[1])
  5196. self.dx = pos[0] - float(self.rel_point1[0])
  5197. self.dy = pos[1] - float(self.rel_point1[1])
  5198. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5199. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5200. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5201. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5202. units = self.defaults["units"].lower()
  5203. self.plotcanvas.text_hud.text = \
  5204. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5205. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5206. self.mouse = [pos[0], pos[1]]
  5207. if self.defaults['global_selection_shape'] is False:
  5208. self.selection_type = None
  5209. return
  5210. # if the mouse is moved and the LMB is clicked then the action is a selection
  5211. if self.event_is_dragging == 1 and event.button == 1:
  5212. self.delete_selection_shape()
  5213. if self.dx < 0:
  5214. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5215. face_color=self.defaults['global_alt_sel_fill'])
  5216. self.selection_type = False
  5217. elif self.dx >= 0:
  5218. self.draw_moving_selection_shape(self.pos, pos)
  5219. self.selection_type = True
  5220. else:
  5221. self.selection_type = None
  5222. else:
  5223. self.selection_type = None
  5224. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5225. if self.defaults['global_hover']:
  5226. for obj in self.collection.get_list():
  5227. try:
  5228. # select the object(s) only if it is enabled (plotted)
  5229. if obj.options['plot']:
  5230. if obj not in self.collection.get_selected():
  5231. poly_obj = Polygon(
  5232. [(obj.options['xmin'], obj.options['ymin']),
  5233. (obj.options['xmax'], obj.options['ymin']),
  5234. (obj.options['xmax'], obj.options['ymax']),
  5235. (obj.options['xmin'], obj.options['ymax'])]
  5236. )
  5237. if Point(pos).within(poly_obj):
  5238. if obj.isHovering is False:
  5239. obj.isHovering = True
  5240. obj.notHovering = True
  5241. # create the selection box around the selected object
  5242. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5243. else:
  5244. if obj.notHovering is True:
  5245. obj.notHovering = False
  5246. obj.isHovering = False
  5247. self.delete_hover_shape()
  5248. except Exception:
  5249. # the Exception here will happen if we try to select on screen and we have an
  5250. # newly (and empty) just created Geometry or Excellon object that do not have the
  5251. # xmin, xmax, ymin, ymax options.
  5252. # In this case poly_obj creation (see above) will fail
  5253. pass
  5254. except Exception as e:
  5255. self.log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5256. self.ui.position_label.setText("")
  5257. self.ui.rel_position_label.setText("")
  5258. self.mouse = None
  5259. def on_mouse_click_release_over_plot(self, event):
  5260. """
  5261. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5262. and has been registered in ''self.__init__()''.
  5263. :param event: contains information about the event.
  5264. :return:
  5265. """
  5266. if self.is_legacy is False:
  5267. event_pos = event.pos
  5268. right_button = 2
  5269. else:
  5270. event_pos = (event.xdata, event.ydata)
  5271. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5272. right_button = 3
  5273. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5274. if self.grid_status():
  5275. try:
  5276. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5277. except TypeError:
  5278. return
  5279. else:
  5280. pos = (pos_canvas[0], pos_canvas[1])
  5281. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5282. # canvas menu
  5283. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5284. self.ui.popMenu.mouse_is_panning = False
  5285. self.cursor = QtGui.QCursor()
  5286. self.populate_cmenu_grids()
  5287. self.ui.popMenu.popup(self.cursor.pos())
  5288. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5289. # selection and then select a type of selection ("enclosing" or "touching")
  5290. if event.button == 1: # left click
  5291. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5292. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5293. if modifiers == QtCore.Qt.ShiftModifier:
  5294. # do not auto open the Project Tab
  5295. self.click_noproject = True
  5296. self.clipboard.setText(
  5297. self.defaults["global_point_clipboard_format"] %
  5298. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5299. )
  5300. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5301. return
  5302. if self.doubleclick is True:
  5303. self.doubleclick = False
  5304. if self.collection.get_selected():
  5305. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5306. if self.ui.splitter.sizes()[0] == 0:
  5307. self.ui.splitter.setSizes([1, 1])
  5308. try:
  5309. # delete the selection shape(S) as it may be in the way
  5310. self.delete_selection_shape()
  5311. self.delete_hover_shape()
  5312. except Exception as e:
  5313. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5314. return
  5315. else:
  5316. # WORKAROUND for LEGACY MODE
  5317. if self.is_legacy is True:
  5318. # if there is no move on canvas then we have no dragging selection
  5319. if self.dx == 0 or self.dy == 0:
  5320. self.selection_type = None
  5321. if self.selection_type is not None:
  5322. try:
  5323. self.selection_area_handler(self.pos, pos, self.selection_type)
  5324. self.selection_type = None
  5325. except Exception as e:
  5326. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5327. return
  5328. else:
  5329. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5330. if key_modifier == QtCore.Qt.ShiftModifier:
  5331. mod_key = 'Shift'
  5332. elif key_modifier == QtCore.Qt.ControlModifier:
  5333. mod_key = 'Control'
  5334. else:
  5335. mod_key = None
  5336. try:
  5337. if self.command_active is None:
  5338. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5339. # deselect, and if it's not selected then it will be selected
  5340. # If there is no active command (self.command_active is None) then we check if we clicked
  5341. # on a object by checking the bounding limits against mouse click position
  5342. if mod_key == self.defaults["global_mselect_key"]:
  5343. self.select_objects(key='multisel')
  5344. else:
  5345. # If there is no active command (self.command_active is None) then we check if
  5346. # we clicked on a object by checking the bounding limits against mouse click position
  5347. self.select_objects()
  5348. self.delete_hover_shape()
  5349. except Exception as e:
  5350. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5351. return
  5352. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5353. """
  5354. :param start_pos: mouse position when the selection LMB click was done
  5355. :param end_pos: mouse position when the left mouse button is released
  5356. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5357. :return:
  5358. """
  5359. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5360. # delete previous selection shape
  5361. self.delete_selection_shape()
  5362. # make all objects inactive
  5363. self.collection.set_all_inactive()
  5364. for obj in self.collection.get_list():
  5365. try:
  5366. # select the object(s) only if it is enabled (plotted)
  5367. if obj.options['plot']:
  5368. # it's a line without area
  5369. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5370. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5371. # it's a geometry with area
  5372. else:
  5373. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5374. (obj.options['xmax'], obj.options['ymin']),
  5375. (obj.options['xmax'], obj.options['ymax']),
  5376. (obj.options['xmin'], obj.options['ymax'])])
  5377. if poly_obj.is_empty or not poly_obj.is_valid:
  5378. continue
  5379. if sel_type is True:
  5380. if poly_obj.within(poly_selection):
  5381. # create the selection box around the selected object
  5382. if self.defaults['global_selection_shape'] is True:
  5383. self.draw_selection_shape(obj)
  5384. self.collection.set_active(obj.options['name'])
  5385. else:
  5386. if poly_selection.intersects(poly_obj):
  5387. # create the selection box around the selected object
  5388. if self.defaults['global_selection_shape'] is True:
  5389. self.draw_selection_shape(obj)
  5390. self.collection.set_active(obj.options['name'])
  5391. obj.selection_shape_drawn = True
  5392. except Exception as e:
  5393. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5394. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5395. # In this case poly_obj creation (see above) will fail
  5396. self.log.debug("App.selection_area_handler() --> %s" % str(e))
  5397. def select_objects(self, key=None):
  5398. """
  5399. Will select objects clicked on canvas
  5400. :param key: for future use in cumulative selection
  5401. :return:
  5402. """
  5403. # list where we store the overlapped objects under our mouse left click position
  5404. if key is None:
  5405. self.objects_under_the_click_list = []
  5406. # Populate the list with the overlapped objects on the click position
  5407. curr_x, curr_y = self.pos
  5408. for obj in self.all_objects_list:
  5409. # ScriptObject and DocumentObject objects can't be selected
  5410. if obj.kind == 'script' or obj.kind == 'document':
  5411. continue
  5412. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5413. continue
  5414. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5415. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5416. if obj.options['name'] not in self.objects_under_the_click_list:
  5417. if obj.options['plot']:
  5418. # add objects to the objects_under_the_click list only if the object is plotted
  5419. # (active and not disabled)
  5420. self.objects_under_the_click_list.append(obj.options['name'])
  5421. try:
  5422. if self.objects_under_the_click_list:
  5423. curr_sel_obj = self.collection.get_active()
  5424. # case when there is only an object under the click and we toggle it
  5425. if len(self.objects_under_the_click_list) == 1:
  5426. if curr_sel_obj is None:
  5427. self.collection.set_active(self.objects_under_the_click_list[0])
  5428. curr_sel_obj = self.collection.get_active()
  5429. # create the selection box around the selected object
  5430. if self.defaults['global_selection_shape'] is True:
  5431. self.draw_selection_shape(curr_sel_obj)
  5432. curr_sel_obj.selection_shape_drawn = True
  5433. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5434. self.collection.on_objects_selection(False)
  5435. self.delete_selection_shape()
  5436. curr_sel_obj.selection_shape_drawn = False
  5437. self.collection.set_active(self.objects_under_the_click_list[0])
  5438. curr_sel_obj = self.collection.get_active()
  5439. # create the selection box around the selected object
  5440. if self.defaults['global_selection_shape'] is True:
  5441. self.draw_selection_shape(curr_sel_obj)
  5442. curr_sel_obj.selection_shape_drawn = True
  5443. self.selected_message(curr_sel_obj=curr_sel_obj)
  5444. elif curr_sel_obj.selection_shape_drawn is False:
  5445. if self.defaults['global_selection_shape'] is True:
  5446. self.draw_selection_shape(curr_sel_obj)
  5447. curr_sel_obj.selection_shape_drawn = True
  5448. else:
  5449. self.collection.on_objects_selection(False)
  5450. self.delete_selection_shape()
  5451. if self.call_source != 'app':
  5452. self.call_source = 'app'
  5453. self.selected_message(curr_sel_obj=curr_sel_obj)
  5454. else:
  5455. # If there is no selected object
  5456. # make active the first element of the overlapped objects list
  5457. if self.collection.get_active() is None:
  5458. self.collection.set_active(self.objects_under_the_click_list[0])
  5459. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5460. name_sel_obj = self.collection.get_active().options['name']
  5461. # In case that there is a selected object but it is not in the overlapped object list
  5462. # make that object inactive and activate the first element in the overlapped object list
  5463. if name_sel_obj not in self.objects_under_the_click_list:
  5464. self.collection.set_inactive(name_sel_obj)
  5465. name_sel_obj = self.objects_under_the_click_list[0]
  5466. self.collection.set_active(name_sel_obj)
  5467. else:
  5468. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5469. self.collection.set_all_inactive()
  5470. self.collection.set_active(
  5471. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5472. curr_sel_obj = self.collection.get_active()
  5473. # delete the possible selection box around a possible selected object
  5474. self.delete_selection_shape()
  5475. curr_sel_obj.selection_shape_drawn = False
  5476. # create the selection box around the selected object
  5477. if self.defaults['global_selection_shape'] is True:
  5478. self.draw_selection_shape(curr_sel_obj)
  5479. curr_sel_obj.selection_shape_drawn = True
  5480. self.selected_message(curr_sel_obj=curr_sel_obj)
  5481. else:
  5482. # deselect everything
  5483. self.collection.on_objects_selection(False)
  5484. # delete the possible selection box around a possible selected object
  5485. self.delete_selection_shape()
  5486. for o in self.collection.get_list():
  5487. o.selection_shape_drawn = False
  5488. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5489. # only when working on App
  5490. if self.call_source == 'app':
  5491. if self.click_noproject is False:
  5492. # if the Tool Tab is in focus don't change focus to Project Tab
  5493. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5494. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5495. else:
  5496. # restore auto open the Project Tab
  5497. self.click_noproject = False
  5498. # delete any text in the status bar, implicitly the last object name that was selected
  5499. # self.inform.emit("")
  5500. else:
  5501. self.call_source = 'app'
  5502. except Exception as e:
  5503. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5504. def selected_message(self, curr_sel_obj):
  5505. if curr_sel_obj:
  5506. if curr_sel_obj.kind == 'gerber':
  5507. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5508. color='green',
  5509. name=str(curr_sel_obj.options['name']),
  5510. tx=_("selected"))
  5511. )
  5512. elif curr_sel_obj.kind == 'excellon':
  5513. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5514. color='brown',
  5515. name=str(curr_sel_obj.options['name']),
  5516. tx=_("selected"))
  5517. )
  5518. elif curr_sel_obj.kind == 'cncjob':
  5519. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5520. color='blue',
  5521. name=str(curr_sel_obj.options['name']),
  5522. tx=_("selected"))
  5523. )
  5524. elif curr_sel_obj.kind == 'geometry':
  5525. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5526. color='red',
  5527. name=str(curr_sel_obj.options['name']),
  5528. tx=_("selected"))
  5529. )
  5530. def delete_hover_shape(self):
  5531. self.hover_shapes.clear()
  5532. self.hover_shapes.redraw()
  5533. def draw_hover_shape(self, sel_obj, color=None):
  5534. """
  5535. :param sel_obj: The object for which the hover shape must be drawn
  5536. :param color: The color of the hover shape
  5537. :return: None
  5538. """
  5539. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5540. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5541. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5542. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5543. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5544. if self.defaults['units'].upper() == 'MM':
  5545. hover_rect = hover_rect.buffer(-0.1)
  5546. hover_rect = hover_rect.buffer(0.2)
  5547. else:
  5548. hover_rect = hover_rect.buffer(-0.00393)
  5549. hover_rect = hover_rect.buffer(0.00787)
  5550. # if color:
  5551. # face = Color(color)
  5552. # face.alpha = 0.2
  5553. # outline = Color(color, alpha=0.8)
  5554. # else:
  5555. # face = Color(self.defaults['global_sel_fill'])
  5556. # face.alpha = 0.2
  5557. # outline = self.defaults['global_sel_line']
  5558. if color:
  5559. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5560. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5561. else:
  5562. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5563. outline = self.defaults['global_sel_line']
  5564. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5565. if self.is_legacy is True:
  5566. self.hover_shapes.redraw()
  5567. def delete_selection_shape(self):
  5568. self.move_tool.sel_shapes.clear()
  5569. self.move_tool.sel_shapes.redraw()
  5570. def draw_selection_shape(self, sel_obj, color=None):
  5571. """
  5572. Will draw a selection shape around the selected object.
  5573. :param sel_obj: The object for which the selection shape must be drawn
  5574. :param color: The color for the selection shape.
  5575. :return: None
  5576. """
  5577. if sel_obj is None:
  5578. return
  5579. # it's a line without area
  5580. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5581. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5582. # it's a geometry with area
  5583. else:
  5584. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5585. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5586. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5587. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5588. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5589. b_sel_rect = None
  5590. try:
  5591. if self.defaults['units'].upper() == 'MM':
  5592. b_sel_rect = sel_rect.buffer(-0.1)
  5593. b_sel_rect = b_sel_rect.buffer(0.2)
  5594. else:
  5595. b_sel_rect = sel_rect.buffer(-0.00393)
  5596. b_sel_rect = b_sel_rect.buffer(0.00787)
  5597. except Exception:
  5598. pass
  5599. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5600. b_sel_rect = sel_rect
  5601. if color:
  5602. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5603. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5604. else:
  5605. if self.is_legacy is False:
  5606. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5607. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5608. else:
  5609. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5610. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5611. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5612. color=outline,
  5613. face_color=face,
  5614. update=True,
  5615. layer=0,
  5616. tolerance=None))
  5617. if self.is_legacy is True:
  5618. self.move_tool.sel_shapes.redraw()
  5619. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5620. """
  5621. Will draw a selection shape when dragging mouse on canvas.
  5622. :param old_coords: Old coordinates
  5623. :param coords: New coordinates
  5624. :param kwargs: Keyword arguments
  5625. :return:
  5626. """
  5627. if 'color' in kwargs:
  5628. color = kwargs['color']
  5629. else:
  5630. color = self.defaults['global_sel_line']
  5631. if 'face_color' in kwargs:
  5632. face_color = kwargs['face_color']
  5633. else:
  5634. face_color = self.defaults['global_sel_fill']
  5635. if 'face_alpha' in kwargs:
  5636. face_alpha = kwargs['face_alpha']
  5637. else:
  5638. face_alpha = 0.3
  5639. x0, y0 = old_coords
  5640. x1, y1 = coords
  5641. pt1 = (x0, y0)
  5642. pt2 = (x1, y0)
  5643. pt3 = (x1, y1)
  5644. pt4 = (x0, y1)
  5645. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5646. # color_t = Color(face_color)
  5647. # color_t.alpha = face_alpha
  5648. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5649. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5650. layer=0, tolerance=None)
  5651. if self.is_legacy is True:
  5652. self.move_tool.sel_shapes.redraw()
  5653. def obj_properties(self):
  5654. """
  5655. Will launch the object Properties Tool
  5656. :return:
  5657. """
  5658. self.defaults.report_usage("obj_properties()")
  5659. self.properties_tool.run(toggle=False)
  5660. def on_project_context_save(self):
  5661. """
  5662. Wrapper, will save the object function of it's type
  5663. :return:
  5664. """
  5665. sel_objects = self.collection.get_selected()
  5666. len_objects = len(sel_objects)
  5667. cnt = 0
  5668. if len_objects > 1:
  5669. for o in sel_objects:
  5670. if o.kind == 'cncjob':
  5671. cnt += 1
  5672. if len_objects == cnt:
  5673. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5674. _filter_ = self.defaults['cncjob_save_filters'] + \
  5675. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5676. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5677. try:
  5678. filename, _f = FCFileSaveDialog.get_saved_filename(
  5679. caption=_("Export Code ..."),
  5680. directory=dir_file_to_save,
  5681. ext_filter=_filter_
  5682. )
  5683. except TypeError:
  5684. filename, _f = FCFileSaveDialog.get_saved_filename(
  5685. caption=_("Export Code ..."),
  5686. ext_filter=_filter_)
  5687. filename = filename.rpartition('/')[0]
  5688. for ob in sel_objects:
  5689. ob.read_form()
  5690. fname = '%s/%s' % (filename, ob.options['name'])
  5691. ob.export_gcode_handler(fname, is_gcode=True)
  5692. return
  5693. obj = self.collection.get_active()
  5694. if type(obj) == GeometryObject:
  5695. self.on_file_exportdxf()
  5696. elif type(obj) == ExcellonObject:
  5697. self.on_file_saveexcellon()
  5698. elif type(obj) == CNCJobObject:
  5699. obj.on_exportgcode_button_click()
  5700. elif type(obj) == GerberObject:
  5701. self.on_file_savegerber()
  5702. elif type(obj) == ScriptObject:
  5703. self.on_file_savescript()
  5704. elif type(obj) == DocumentObject:
  5705. self.on_file_savedocument()
  5706. def obj_move(self):
  5707. """
  5708. Callback for the Move menu entry in various Context Menu's.
  5709. :return:
  5710. """
  5711. self.defaults.report_usage("obj_move()")
  5712. self.move_tool.run(toggle=False)
  5713. # ###############################################################################################################
  5714. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5715. # ###############################################################################################################
  5716. def init_code_editor(self, name):
  5717. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5718. # add the tab if it was closed
  5719. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5720. self.text_editor_tab.setObjectName('text_editor_tab')
  5721. # delete the absolute and relative position and messages in the infobar
  5722. # self.ui.position_label.setText("")
  5723. # self.ui.rel_position_label.setText("")
  5724. # hide coordinates toolbars in the infobar while in DB
  5725. self.ui.coords_toolbar.hide()
  5726. self.ui.delta_coords_toolbar.hide()
  5727. self.toggle_codeeditor = True
  5728. self.text_editor_tab.code_editor.completer_enable = False
  5729. self.text_editor_tab.buttonRun.hide()
  5730. # make sure to keep a reference to the code editor
  5731. self.reference_code_editor = self.text_editor_tab.code_editor
  5732. # Switch plot_area to CNCJob tab
  5733. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5734. def on_view_source(self):
  5735. """
  5736. Called when the user wants to see the source file of the selected object
  5737. :return:
  5738. """
  5739. try:
  5740. obj = self.collection.get_active()
  5741. except Exception as e:
  5742. self.log.debug("App.on_view_source() --> %s" % str(e))
  5743. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5744. return 'fail'
  5745. if obj is None:
  5746. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5747. return 'fail'
  5748. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5749. self.proc_container.view.set_busy(_("Loading..."))
  5750. flt = "All Files (*.*)"
  5751. if obj.kind == 'gerber':
  5752. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5753. elif obj.kind == 'excellon':
  5754. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5755. elif obj.kind == 'cncjob':
  5756. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5757. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5758. # add the tab if it was closed
  5759. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5760. self.source_editor_tab.setObjectName('source_editor_tab')
  5761. # delete the absolute and relative position and messages in the infobar
  5762. # self.ui.position_label.setText("")
  5763. # self.ui.rel_position_label.setText("")
  5764. # hide coordinates toolbars in the infobar while in DB
  5765. self.ui.coords_toolbar.hide()
  5766. self.ui.delta_coords_toolbar.hide()
  5767. self.source_editor_tab.code_editor.completer_enable = False
  5768. self.source_editor_tab.buttonRun.hide()
  5769. # Switch plot_area to CNCJob tab
  5770. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5771. try:
  5772. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5773. except TypeError:
  5774. pass
  5775. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5776. try:
  5777. self.source_editor_tab.buttonSave.clicked.disconnect()
  5778. except TypeError:
  5779. pass
  5780. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5781. # then append the text from GCode to the text editor
  5782. if obj.kind == 'cncjob':
  5783. try:
  5784. file = obj.export_gcode(to_file=True)
  5785. if file == 'fail':
  5786. return 'fail'
  5787. except AttributeError:
  5788. self.inform.emit('[WARNING_NOTCL] %s' %
  5789. _("There is no selected object for which to see it's source file code."))
  5790. return 'fail'
  5791. else:
  5792. try:
  5793. file = StringIO(obj.source_file)
  5794. except (AttributeError, TypeError):
  5795. self.inform.emit('[WARNING_NOTCL] %s' %
  5796. _("There is no selected object for which to see it's source file code."))
  5797. return 'fail'
  5798. self.source_editor_tab.t_frame.hide()
  5799. try:
  5800. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5801. except Exception as e:
  5802. self.log.debug('App.on_view_source() -->%s' % str(e))
  5803. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5804. return
  5805. self.source_editor_tab.t_frame.show()
  5806. self.proc_container.view.set_idle()
  5807. # self.ui.show()
  5808. def on_toggle_code_editor(self):
  5809. self.defaults.report_usage("on_toggle_code_editor()")
  5810. if self.toggle_codeeditor is False:
  5811. self.init_code_editor(name=_("Code Editor"))
  5812. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5813. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5814. self.text_editor_tab.buttonSave.clicked.disconnect()
  5815. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5816. else:
  5817. for idx in range(self.ui.plot_tab_area.count()):
  5818. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5819. self.ui.plot_tab_area.closeTab(idx)
  5820. break
  5821. self.toggle_codeeditor = False
  5822. def on_code_editor_close(self):
  5823. self.toggle_codeeditor = False
  5824. def goto_text_line(self):
  5825. """
  5826. Will scroll a text to the specified text line.
  5827. :return: None
  5828. """
  5829. dia_box = Dialog_box(title=_("Go to Line ..."),
  5830. label=_("Line:"),
  5831. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5832. initial_text='')
  5833. try:
  5834. line = int(dia_box.location) - 1
  5835. except (ValueError, TypeError):
  5836. line = 0
  5837. if dia_box.ok:
  5838. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5839. # at the top of the window
  5840. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5841. # get the document() of the AppTextEditor
  5842. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5843. # create a Text Cursor based on the searched line
  5844. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5845. # set cursor of the code editor with the cursor at the searcehd line
  5846. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5847. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5848. """
  5849. Re-generates all plots from all objects.
  5850. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5851. :param muted: if True don't print messages
  5852. :param use_thread: if True will use threading for plotting the objects
  5853. :return: None
  5854. """
  5855. self.log.debug("Plot_all()")
  5856. if muted is not True:
  5857. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5858. for plot_obj in self.collection.get_list():
  5859. def worker_task(obj):
  5860. with self.proc_container.new("Plotting"):
  5861. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5862. if fit_view is True:
  5863. self.app_obj.object_plotted.emit(obj)
  5864. if use_thread is True:
  5865. # Send to worker
  5866. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5867. else:
  5868. worker_task(plot_obj)
  5869. def register_folder(self, filename):
  5870. """
  5871. Register the last folder used by the app to open something
  5872. :param filename: the last folder is extracted from the filename
  5873. :return: None
  5874. """
  5875. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5876. def register_save_folder(self, filename):
  5877. """
  5878. Register the last folder used by the app to save something
  5879. :param filename: the last folder is extracted from the filename
  5880. :return: None
  5881. """
  5882. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5883. # def set_progress_bar(self, percentage, text=""):
  5884. # """
  5885. # Set a progress bar to a value (percentage)
  5886. #
  5887. # :param percentage: Value set to the progressbar
  5888. # :param text: Not used
  5889. # :return: None
  5890. # """
  5891. # self.ui.progress_bar.setValue(int(percentage))
  5892. def setup_recent_items(self):
  5893. """
  5894. Setup a dictionary with the recent files accessed, organized by type
  5895. :return:
  5896. """
  5897. icons = {
  5898. "gerber": self.resource_location + "/flatcam_icon16.png",
  5899. "excellon": self.resource_location + "/drill16.png",
  5900. 'geometry': self.resource_location + "/geometry16.png",
  5901. "cncjob": self.resource_location + "/cnc16.png",
  5902. "script": self.resource_location + "/script_new24.png",
  5903. "document": self.resource_location + "/notes16_1.png",
  5904. "project": self.resource_location + "/project16.png",
  5905. "svg": self.resource_location + "/geometry16.png",
  5906. "dxf": self.resource_location + "/dxf16.png",
  5907. "pdf": self.resource_location + "/pdf32.png",
  5908. "image": self.resource_location + "/image16.png"
  5909. }
  5910. try:
  5911. image_opener = self.image_tool.import_image
  5912. except AttributeError:
  5913. image_opener = None
  5914. openers = {
  5915. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5916. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5917. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5918. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5919. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5920. "document": None,
  5921. 'project': self.f_handlers.open_project,
  5922. 'svg': self.f_handlers.import_svg,
  5923. 'dxf': self.f_handlers.import_dxf,
  5924. 'image': image_opener,
  5925. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5926. }
  5927. # Open recent file for files
  5928. try:
  5929. f = open(self.data_path + '/recent.json')
  5930. except IOError:
  5931. App.log.error("Failed to load recent item list.")
  5932. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5933. return
  5934. try:
  5935. self.recent = json.load(f)
  5936. except json.errors.JSONDecodeError:
  5937. App.log.error("Failed to parse recent item list.")
  5938. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5939. f.close()
  5940. return
  5941. f.close()
  5942. # Open recent file for projects
  5943. try:
  5944. fp = open(self.data_path + '/recent_projects.json')
  5945. except IOError:
  5946. App.log.error("Failed to load recent project item list.")
  5947. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5948. return
  5949. try:
  5950. self.recent_projects = json.load(fp)
  5951. except json.errors.JSONDecodeError:
  5952. App.log.error("Failed to parse recent project item list.")
  5953. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5954. fp.close()
  5955. return
  5956. fp.close()
  5957. # Closure needed to create callbacks in a loop.
  5958. # Otherwise late binding occurs.
  5959. def make_callback(func, fname):
  5960. def opener():
  5961. func(fname)
  5962. return opener
  5963. def reset_recent_files():
  5964. # Reset menu
  5965. self.ui.recent.clear()
  5966. self.recent = []
  5967. try:
  5968. ff = open(self.data_path + '/recent.json', 'w')
  5969. except IOError:
  5970. App.log.error("Failed to open recent items file for writing.")
  5971. return
  5972. json.dump(self.recent, ff)
  5973. def reset_recent_projects():
  5974. # Reset menu
  5975. self.ui.recent_projects.clear()
  5976. self.recent_projects = []
  5977. try:
  5978. frp = open(self.data_path + '/recent_projects.json', 'w')
  5979. except IOError:
  5980. App.log.error("Failed to open recent projects items file for writing.")
  5981. return
  5982. json.dump(self.recent, frp)
  5983. # Reset menu
  5984. self.ui.recent.clear()
  5985. self.ui.recent_projects.clear()
  5986. # Create menu items for projects
  5987. for recent in self.recent_projects:
  5988. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5989. if recent['kind'] == 'project':
  5990. try:
  5991. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5992. # Attach callback
  5993. o = make_callback(openers[recent["kind"]], recent['filename'])
  5994. action.triggered.connect(o)
  5995. self.ui.recent_projects.addAction(action)
  5996. except KeyError:
  5997. App.log.error("Unsupported file type: %s" % recent["kind"])
  5998. # Last action in Recent Files menu is one that Clear the content
  5999. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  6000. (_("Clear Recent projects")), self)
  6001. clear_action_proj.triggered.connect(reset_recent_projects)
  6002. self.ui.recent_projects.addSeparator()
  6003. self.ui.recent_projects.addAction(clear_action_proj)
  6004. # Create menu items for files
  6005. for recent in self.recent:
  6006. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6007. if recent['kind'] != 'project':
  6008. try:
  6009. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6010. # Attach callback
  6011. o = make_callback(openers[recent["kind"]], recent['filename'])
  6012. action.triggered.connect(o)
  6013. self.ui.recent.addAction(action)
  6014. except KeyError:
  6015. App.log.error("Unsupported file type: %s" % recent["kind"])
  6016. # Last action in Recent Files menu is one that Clear the content
  6017. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  6018. (_("Clear Recent files")), self)
  6019. clear_action.triggered.connect(reset_recent_files)
  6020. self.ui.recent.addSeparator()
  6021. self.ui.recent.addAction(clear_action)
  6022. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6023. # self.ui.menufilerecent.set_submenu(recent_menu)
  6024. # recent_menu.show_all()
  6025. # self.ui.recent.show()
  6026. self.log.debug("Recent items list has been populated.")
  6027. def on_properties_tab_click(self, index):
  6028. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  6029. self.setup_default_properties_tab()
  6030. def setup_default_properties_tab(self):
  6031. """
  6032. Default text for the Properties tab when is not taken by the Object UI.
  6033. :return:
  6034. """
  6035. # label = QtWidgets.QLabel("Choose an item from Project")
  6036. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6037. # sel_title = QtWidgets.QTextEdit()
  6038. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6039. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6040. #
  6041. # f_settings = QSettings("Open Source", "FlatCAM")
  6042. # if f_settings.contains("notebook_font_size"):
  6043. # fsize = f_settings.value('notebook_font_size', type=int)
  6044. # else:
  6045. # fsize = 12
  6046. #
  6047. # tsize = fsize + int(fsize / 2)
  6048. #
  6049. # selected_text = ''
  6050. #
  6051. # sel_title.setText(selected_text)
  6052. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6053. # Tree Widget
  6054. d_properties_tw = FCTree(columns=2)
  6055. d_properties_tw.setObjectName("default_properties")
  6056. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6057. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  6058. root = d_properties_tw.invisibleRootItem()
  6059. font = QtGui.QFont()
  6060. font.setBold(True)
  6061. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6062. # main Items categories
  6063. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6064. d_properties_tw.addChild(parent=general_cat,
  6065. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6066. d_properties_tw.addChild(parent=general_cat,
  6067. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6068. d_properties_tw.addChild(parent=general_cat,
  6069. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6070. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6071. d_properties_tw.addChild(parent=grid_cat,
  6072. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6073. column1=True)
  6074. d_properties_tw.addChild(parent=grid_cat,
  6075. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6076. column1=True)
  6077. d_properties_tw.addChild(parent=grid_cat,
  6078. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6079. column1=True)
  6080. d_properties_tw.addChild(parent=grid_cat,
  6081. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6082. column1=True)
  6083. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6084. d_properties_tw.addChild(parent=canvas_cat,
  6085. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6086. column1=True)
  6087. d_properties_tw.addChild(parent=canvas_cat,
  6088. title=['%s:' % _("Workspace active"),
  6089. '%s' % str(self.defaults['global_workspace'])],
  6090. column1=True)
  6091. d_properties_tw.addChild(parent=canvas_cat,
  6092. title=['%s:' % _("Workspace size"),
  6093. '%s' % str(self.defaults['global_workspaceT'])],
  6094. column1=True)
  6095. d_properties_tw.addChild(parent=canvas_cat,
  6096. title=['%s:' % _("Workspace orientation"),
  6097. '%s' % _("Portrait") if self.defaults[
  6098. 'global_workspace_orientation'] == 'p' else
  6099. _("Landscape")],
  6100. column1=True)
  6101. d_properties_tw.addChild(parent=canvas_cat,
  6102. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6103. column1=True)
  6104. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6105. def setup_obj_classes(self):
  6106. """
  6107. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6108. class.
  6109. :return: None
  6110. """
  6111. FlatCAMObj.app = self
  6112. ObjectCollection.app = self
  6113. Gerber.app = self
  6114. Excellon.app = self
  6115. Geometry.app = self
  6116. CNCjob.app = self
  6117. FCProcess.app = self
  6118. FCProcessContainer.app = self
  6119. OptionsGroupUI.app = self
  6120. def version_check(self):
  6121. """
  6122. Checks for the latest version of the program. Alerts the
  6123. user if theirs is outdated. This method is meant to be run
  6124. in a separate thread.
  6125. :return: None
  6126. """
  6127. self.log.debug("version_check()")
  6128. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6129. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6130. App.version_url,
  6131. str(self.defaults['global_serial']),
  6132. str(self.version),
  6133. str(self.os),
  6134. urllib.parse.urlencode(self.defaults["global_stats"])
  6135. )
  6136. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6137. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6138. # urllib.parse.urlencode(self.defaults["global_stats"])
  6139. else:
  6140. # no_stats dict; just so it won't break things on website
  6141. no_ststs_dict = {}
  6142. no_ststs_dict["global_ststs"] = {}
  6143. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6144. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6145. self.log.debug("Checking for updates @ %s" % full_url)
  6146. # ## Get the data
  6147. try:
  6148. f = urllib.request.urlopen(full_url)
  6149. except Exception:
  6150. # App.log.warning("Failed checking for latest version. Could not connect.")
  6151. self.log.warning("Failed checking for latest version. Could not connect.")
  6152. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6153. return
  6154. try:
  6155. data = json.load(f)
  6156. except Exception as e:
  6157. App.log.error("Could not parse information about latest version.")
  6158. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6159. self.log.debug("json.load(): %s" % str(e))
  6160. f.close()
  6161. return
  6162. f.close()
  6163. # ## Latest version?
  6164. if self.version >= data["version"]:
  6165. self.log.debug("FlatCAM is up to date!")
  6166. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6167. return
  6168. self.log.debug("Newer version available.")
  6169. self.message.emit(
  6170. _("Newer Version Available"),
  6171. '%s<br><br>><b>%s</b><br>%s' % (
  6172. _("There is a newer version of FlatCAM available for download:"),
  6173. str(data["name"]),
  6174. str(data["message"])
  6175. ),
  6176. _("info")
  6177. )
  6178. def on_plotcanvas_setup(self, container=None):
  6179. """
  6180. This is doing the setup for the plot area (canvas).
  6181. :param container: QT Widget where to install the canvas
  6182. :return: None
  6183. """
  6184. if container:
  6185. plot_container = container
  6186. else:
  6187. plot_container = self.ui.right_layout
  6188. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6189. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6190. self.is_legacy = True
  6191. self.defaults["global_graphic_engine"] = "2D"
  6192. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6193. else:
  6194. try:
  6195. self.plotcanvas = PlotCanvas(plot_container, self)
  6196. except Exception as er:
  6197. msg_txt = traceback.format_exc()
  6198. self.log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6199. self.log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6200. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6201. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6202. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6203. msg += msg_txt
  6204. self.inform.emit(msg)
  6205. return 'fail'
  6206. # So it can receive key presses
  6207. self.plotcanvas.native.setFocus()
  6208. if self.is_legacy is False:
  6209. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6210. # Set the mouse button for panning
  6211. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6212. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6213. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6214. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6215. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6216. # Keys over plot enabled
  6217. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6218. if self.defaults['global_cursor_type'] == 'small':
  6219. self.app_cursor = self.plotcanvas.new_cursor()
  6220. else:
  6221. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6222. if self.ui.grid_snap_btn.isChecked():
  6223. self.app_cursor.enabled = True
  6224. else:
  6225. self.app_cursor.enabled = False
  6226. if self.is_legacy is False:
  6227. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6228. else:
  6229. # will use the default Matplotlib axes
  6230. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6231. def on_zoom_fit(self):
  6232. """
  6233. Callback for zoom-fit request. This can be either from the corresponding
  6234. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6235. with axes limits from the geometry bounds of all objects.
  6236. :return: None
  6237. """
  6238. if self.is_legacy is False:
  6239. self.plotcanvas.fit_view()
  6240. else:
  6241. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6242. width = xmax - xmin
  6243. height = ymax - ymin
  6244. xmin -= 0.05 * width
  6245. xmax += 0.05 * width
  6246. ymin -= 0.05 * height
  6247. ymax += 0.05 * height
  6248. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6249. def on_zoom_in(self):
  6250. """
  6251. Callback for zoom-in request.
  6252. :return:
  6253. """
  6254. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6255. def on_zoom_out(self):
  6256. """
  6257. Callback for zoom-out request.
  6258. :return:
  6259. """
  6260. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6261. def disable_all_plots(self):
  6262. self.defaults.report_usage("disable_all_plots()")
  6263. self.disable_plots(self.collection.get_list())
  6264. self.inform.emit('[success] %s' % _("All plots disabled."))
  6265. def disable_other_plots(self):
  6266. self.defaults.report_usage("disable_other_plots()")
  6267. self.disable_plots(self.collection.get_non_selected())
  6268. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6269. def enable_all_plots(self):
  6270. self.defaults.report_usage("enable_all_plots()")
  6271. self.enable_plots(self.collection.get_list())
  6272. self.inform.emit('[success] %s' % _("All plots enabled."))
  6273. def enable_other_plots(self):
  6274. self.defaults.report_usage("enable_other_plots()")
  6275. self.enable_plots(self.collection.get_non_selected())
  6276. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6277. def on_enable_sel_plots(self):
  6278. self.log.debug("App.on_enable_sel_plot()")
  6279. object_list = self.collection.get_selected()
  6280. self.enable_plots(objects=object_list)
  6281. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6282. def on_disable_sel_plots(self):
  6283. self.log.debug("App.on_disable_sel_plot()")
  6284. # self.inform.emit(_("Disabling plots ..."))
  6285. object_list = self.collection.get_selected()
  6286. self.disable_plots(objects=object_list)
  6287. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6288. def enable_plots(self, objects):
  6289. """
  6290. Enable plots
  6291. :param objects: list of Objects to be enabled
  6292. :return:
  6293. """
  6294. self.log.debug("Enabling plots ...")
  6295. # self.inform.emit(_("Working ..."))
  6296. for obj in objects:
  6297. if obj.options['plot'] is False:
  6298. obj.options.set_change_callback(lambda x: None)
  6299. obj.options['plot'] = True
  6300. try:
  6301. # only the Gerber obj has on_plot_cb_click() method
  6302. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6303. # disable this cb while disconnected,
  6304. # in case the operation takes time the user is not allowed to change it
  6305. obj.ui.plot_cb.setDisabled(True)
  6306. except AttributeError:
  6307. pass
  6308. obj.set_form_item("plot")
  6309. try:
  6310. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6311. obj.ui.plot_cb.setDisabled(False)
  6312. except AttributeError:
  6313. pass
  6314. obj.options.set_change_callback(obj.on_options_change)
  6315. self.collection.update_view()
  6316. def worker_task(objs):
  6317. with self.proc_container.new(_("Enabling plots ...")):
  6318. for plot_obj in objs:
  6319. # obj.options['plot'] = True
  6320. if isinstance(plot_obj, CNCJobObject):
  6321. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6322. else:
  6323. plot_obj.plot(visible=True)
  6324. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6325. def disable_plots(self, objects):
  6326. """
  6327. Disables plots
  6328. :param objects: list of Objects to be disabled
  6329. :return:
  6330. """
  6331. self.log.debug("Disabling plots ...")
  6332. # self.inform.emit(_("Working ..."))
  6333. for obj in objects:
  6334. if obj.options['plot'] is True:
  6335. obj.options.set_change_callback(lambda x: None)
  6336. obj.options['plot'] = False
  6337. try:
  6338. # only the Gerber obj has on_plot_cb_click() method
  6339. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6340. obj.ui.plot_cb.setDisabled(True)
  6341. except AttributeError:
  6342. pass
  6343. obj.set_form_item("plot")
  6344. try:
  6345. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6346. obj.ui.plot_cb.setDisabled(False)
  6347. except AttributeError:
  6348. pass
  6349. obj.options.set_change_callback(obj.on_options_change)
  6350. try:
  6351. self.delete_selection_shape()
  6352. except Exception as e:
  6353. self.log.debug("App.disable_plots() --> %s" % str(e))
  6354. self.collection.update_view()
  6355. def worker_task(objs):
  6356. with self.proc_container.new(_("Disabling plots ...")):
  6357. for plot_obj in objs:
  6358. # obj.options['plot'] = True
  6359. if isinstance(plot_obj, CNCJobObject):
  6360. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6361. else:
  6362. plot_obj.plot(visible=False)
  6363. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6364. def toggle_plots(self, objects):
  6365. """
  6366. Toggle plots visibility
  6367. :param objects: list of Objects for which to be toggled the visibility
  6368. :return: None
  6369. """
  6370. # if no objects selected then do nothing
  6371. if not self.collection.get_selected():
  6372. return
  6373. self.log.debug("Toggling plots ...")
  6374. self.inform.emit(_("Working ..."))
  6375. for obj in objects:
  6376. if obj.options['plot'] is False:
  6377. obj.options['plot'] = True
  6378. else:
  6379. obj.options['plot'] = False
  6380. self.app_obj.plots_updated.emit()
  6381. def clear_plots(self):
  6382. """
  6383. Clear the plots
  6384. :return: None
  6385. """
  6386. objects = self.collection.get_list()
  6387. for obj in objects:
  6388. obj.clear(obj == objects[-1])
  6389. # Clear pool to free memory
  6390. self.clear_pool()
  6391. def on_set_color_action_triggered(self):
  6392. """
  6393. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6394. :return:
  6395. """
  6396. new_color = self.defaults['gerber_plot_fill']
  6397. clicked_action = self.sender()
  6398. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6399. act_name = clicked_action.text()
  6400. sel_obj_list = self.collection.get_selected()
  6401. if not sel_obj_list:
  6402. return
  6403. # a default value, I just chose this one
  6404. alpha_level = 'BF'
  6405. for sel_obj in sel_obj_list:
  6406. if sel_obj.kind == 'excellon':
  6407. alpha_level = str(hex(
  6408. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6409. elif sel_obj.kind == 'gerber':
  6410. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6411. elif sel_obj.kind == 'geometry':
  6412. alpha_level = 'FF'
  6413. else:
  6414. self.log.debug(
  6415. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6416. continue
  6417. sel_obj.alpha_level = alpha_level
  6418. if act_name == _('Red'):
  6419. new_color = '#FF0000' + alpha_level
  6420. if act_name == _('Blue'):
  6421. new_color = '#0000FF' + alpha_level
  6422. if act_name == _('Yellow'):
  6423. new_color = '#FFDF00' + alpha_level
  6424. if act_name == _('Green'):
  6425. new_color = '#00FF00' + alpha_level
  6426. if act_name == _('Purple'):
  6427. new_color = '#FF00FF' + alpha_level
  6428. if act_name == _('Brown'):
  6429. new_color = '#A52A2A' + alpha_level
  6430. if act_name == _('White'):
  6431. new_color = '#FFFFFF' + alpha_level
  6432. if act_name == _('Black'):
  6433. new_color = '#000000' + alpha_level
  6434. if act_name == _('Custom'):
  6435. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6436. c_dialog = QtWidgets.QColorDialog()
  6437. plot_fill_color = c_dialog.getColor(initial=new_color)
  6438. if plot_fill_color.isValid() is False:
  6439. return
  6440. new_color = str(plot_fill_color.name()) + alpha_level
  6441. if act_name == _("Default"):
  6442. for sel_obj in sel_obj_list:
  6443. if sel_obj.kind == 'excellon':
  6444. new_color = self.defaults['excellon_plot_fill']
  6445. new_line_color = self.defaults['excellon_plot_line']
  6446. elif sel_obj.kind == 'gerber':
  6447. new_color = self.defaults['gerber_plot_fill']
  6448. new_line_color = self.defaults['gerber_plot_line']
  6449. elif sel_obj.kind == 'geometry':
  6450. new_color = self.defaults['geometry_plot_line']
  6451. new_line_color = self.defaults['geometry_plot_line']
  6452. else:
  6453. self.log.debug(
  6454. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6455. continue
  6456. sel_obj.fill_color = new_color
  6457. sel_obj.outline_color = new_line_color
  6458. sel_obj.shapes.redraw(
  6459. update_colors=(new_color, new_line_color)
  6460. )
  6461. return
  6462. if act_name == _("Opacity"):
  6463. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6464. # '%s:' % _("Value"),
  6465. # min=0, max=255, step=1, value=191)
  6466. alpha_dialog = FCInputDialogSlider(
  6467. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6468. alpha_level, ok_button = alpha_dialog.get_results()
  6469. if ok_button:
  6470. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6471. for sel_obj in sel_obj_list:
  6472. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6473. sel_obj.shapes.redraw(
  6474. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6475. )
  6476. return
  6477. new_line_color = color_variant(new_color[:7], 0.7)
  6478. if act_name == _("White"):
  6479. new_line_color = color_variant("#dedede", 0.7)
  6480. for sel_obj in sel_obj_list:
  6481. sel_obj.fill_color = new_color
  6482. sel_obj.outline_color = new_line_color
  6483. sel_obj.shapes.redraw(
  6484. update_colors=(new_color, new_line_color)
  6485. )
  6486. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6487. group = self.collection.group_items["gerber"]
  6488. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6489. new_c = (new_line_color, new_color)
  6490. for sel_obj in sel_obj_list:
  6491. if sel_obj.kind == 'gerber':
  6492. item = sel_obj.item
  6493. item_index = self.collection.index(item.row(), 0, group_index)
  6494. idx = item_index.row()
  6495. self.defaults["gerber_color_list"][idx] = new_c
  6496. def generate_cnc_job(self, objects):
  6497. """
  6498. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6499. :param objects: Selected objects in the Project Tab
  6500. :return:
  6501. """
  6502. self.defaults.report_usage("generate_cnc_job()")
  6503. # for obj in objects:
  6504. # obj.generatecncjob()
  6505. for obj in objects:
  6506. obj.on_generatecnc_button_click()
  6507. def start_delayed_quit(self, delay, filename, should_quit=None):
  6508. """
  6509. :param delay: period of checking if project file size is more than zero; in seconds
  6510. :param filename: the name of the project file to be checked periodically for size more than zero
  6511. :param should_quit: if the task finished will be followed by an app quit; boolean
  6512. :return:
  6513. """
  6514. to_quit = should_quit
  6515. self.save_timer = QtCore.QTimer()
  6516. self.save_timer.setInterval(delay)
  6517. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6518. self.save_timer.start()
  6519. def check_project_file_size(self, filename, should_quit=None):
  6520. """
  6521. :param filename: the name of the project file to be checked periodically for size more than zero
  6522. :param should_quit: will quit the app if True; boolean
  6523. :return:
  6524. """
  6525. try:
  6526. if os.stat(filename).st_size > 0:
  6527. self.save_in_progress = False
  6528. self.save_timer.stop()
  6529. if should_quit:
  6530. self.app_quit.emit()
  6531. except Exception:
  6532. traceback.print_exc()
  6533. def save_project_auto(self):
  6534. """
  6535. Called periodically to save the project.
  6536. 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
  6537. # progress.
  6538. :return:
  6539. """
  6540. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6541. self.on_file_saveproject()
  6542. def save_project_auto_update(self):
  6543. """
  6544. Update the auto save time interval value.
  6545. :return:
  6546. """
  6547. self.log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6548. try:
  6549. if self.autosave_timer.isActive():
  6550. self.autosave_timer.stop()
  6551. except Exception:
  6552. pass
  6553. if self.defaults['global_autosave'] is True:
  6554. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6555. self.autosave_timer.start()
  6556. def on_options_app2project(self):
  6557. """
  6558. Callback for Options->Transfer Options->App=>Project. Copies options
  6559. from application defaults to project defaults.
  6560. :return: None
  6561. """
  6562. self.defaults.report_usage("on_options_app2project")
  6563. self.preferencesUiManager.defaults_read_form()
  6564. self.options.update(self.defaults)
  6565. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6566. """
  6567. Shows a message on the FlatCAM Shell
  6568. :param msg: Message to display.
  6569. :param show: Opens the shell.
  6570. :param error: Shows the message as an error.
  6571. :param warning: Shows the message as an warning.
  6572. :param success: Shows the message as an success.
  6573. :param selected: Indicate that something was selected on canvas
  6574. :return: None
  6575. """
  6576. end = '\n' if new_line is True else ''
  6577. if show:
  6578. self.ui.shell_dock.show()
  6579. try:
  6580. if error:
  6581. self.shell.append_error(msg + end)
  6582. elif warning:
  6583. self.shell.append_warning(msg + end)
  6584. elif success:
  6585. self.shell.append_success(msg + end)
  6586. elif selected:
  6587. self.shell.append_selected(msg + end)
  6588. else:
  6589. self.shell.append_output(msg + end)
  6590. except AttributeError:
  6591. self.log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6592. def dec_format(self, val, dec=None):
  6593. """
  6594. Returns a formatted float value with a certain number of decimals
  6595. """
  6596. dec_nr = dec if dec is not None else self.decimals
  6597. return float('%.*f' % (dec_nr, val))
  6598. class ArgsThread(QtCore.QObject):
  6599. open_signal = pyqtSignal(list)
  6600. start = pyqtSignal()
  6601. stop = pyqtSignal()
  6602. if sys.platform == 'win32':
  6603. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6604. else:
  6605. address = ('/tmp/testipc', 'AF_UNIX')
  6606. def __init__(self):
  6607. super().__init__()
  6608. self.listener = None
  6609. self.thread_exit = False
  6610. self.start.connect(self.run)
  6611. self.stop.connect(self.close_listener)
  6612. def my_loop(self, address):
  6613. try:
  6614. self.listener = Listener(*address)
  6615. while self.thread_exit is False:
  6616. conn = self.listener.accept()
  6617. self.serve(conn)
  6618. except socket.error:
  6619. try:
  6620. conn = Client(*address)
  6621. conn.send(sys.argv)
  6622. conn.send('close')
  6623. # close the current instance only if there are args
  6624. if len(sys.argv) > 1:
  6625. try:
  6626. self.listener.close()
  6627. except Exception:
  6628. pass
  6629. sys.exit()
  6630. except ConnectionRefusedError:
  6631. if sys.platform == 'win32':
  6632. pass
  6633. else:
  6634. os.system('rm /tmp/testipc')
  6635. self.listener = Listener(*address)
  6636. while True:
  6637. conn = self.listener.accept()
  6638. self.serve(conn)
  6639. def serve(self, conn):
  6640. while self.thread_exit is False:
  6641. msg = conn.recv()
  6642. if msg == 'close':
  6643. break
  6644. self.open_signal.emit(msg)
  6645. conn.close()
  6646. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6647. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6648. @pyqtSlot()
  6649. def run(self):
  6650. self.my_loop(self.address)
  6651. @pyqtSlot()
  6652. def close_listener(self):
  6653. self.thread_exit = True
  6654. self.listener.close()
  6655. class MenuFileHandlers(QtCore.QObject):
  6656. def __init__(self, app):
  6657. super().__init__()
  6658. self.app = app
  6659. self.inform = self.app.inform
  6660. self.splash = self.app.splash
  6661. self.worker_task = self.app.worker_task
  6662. self.defaults = self.app.defaults
  6663. self.pagesize = {}
  6664. def on_fileopengerber(self, signal, name=None):
  6665. """
  6666. File menu callback for opening a Gerber.
  6667. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6668. :param name:
  6669. :return: None
  6670. """
  6671. self.app.log.debug("on_fileopengerber()")
  6672. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6673. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6674. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6675. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6676. "*.outline);;" \
  6677. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6678. "*.mil);;" \
  6679. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6680. "Allegro Files (*.art);;" \
  6681. "Mentor Files (*.pho *.gdo);;" \
  6682. "All Files (*.*)"
  6683. if name is None:
  6684. try:
  6685. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6686. directory=self.app.get_last_folder(),
  6687. filter=_filter_,
  6688. initialFilter=self.app.last_op_gerber_filter)
  6689. except TypeError:
  6690. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6691. filenames = [str(filename) for filename in filenames]
  6692. self.app.last_op_gerber_filter = _f
  6693. else:
  6694. filenames = [name]
  6695. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6696. "Canvas initialization finished in"),
  6697. '%.2f' % self.app.used_time,
  6698. _("Opening Gerber file.")),
  6699. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6700. color=QtGui.QColor("gray"))
  6701. if len(filenames) == 0:
  6702. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6703. else:
  6704. for filename in filenames:
  6705. if filename != '':
  6706. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6707. def on_fileopenexcellon(self, signal, name=None):
  6708. """
  6709. File menu callback for opening an Excellon file.
  6710. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6711. :param name:
  6712. :return: None
  6713. """
  6714. self.app.log.debug("on_fileopenexcellon()")
  6715. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6716. "All Files (*.*)"
  6717. if name is None:
  6718. try:
  6719. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6720. directory=self.app.get_last_folder(),
  6721. filter=_filter_,
  6722. initialFilter=self.app.last_op_excellon_filter)
  6723. except TypeError:
  6724. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6725. filenames = [str(filename) for filename in filenames]
  6726. self.app.last_op_excellon_filter = _f
  6727. else:
  6728. filenames = [str(name)]
  6729. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6730. "Canvas initialization finished in"),
  6731. '%.2f' % self.app.used_time,
  6732. _("Opening Excellon file.")),
  6733. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6734. color=QtGui.QColor("gray"))
  6735. if len(filenames) == 0:
  6736. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6737. else:
  6738. for filename in filenames:
  6739. if filename != '':
  6740. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6741. def on_fileopengcode(self, signal, name=None):
  6742. """
  6743. File menu call back for opening gcode.
  6744. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6745. :param name:
  6746. :return:
  6747. """
  6748. self.app.log.debug("on_fileopengcode()")
  6749. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6750. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6751. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6752. "All Files (*.*)"
  6753. if name is None:
  6754. try:
  6755. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6756. directory=self.app.get_last_folder(),
  6757. filter=_filter_,
  6758. initialFilter=self.app.last_op_gcode_filter)
  6759. except TypeError:
  6760. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6761. filenames = [str(filename) for filename in filenames]
  6762. self.app.last_op_gcode_filter = _f
  6763. else:
  6764. filenames = [name]
  6765. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6766. "Canvas initialization finished in"),
  6767. '%.2f' % self.app.used_time,
  6768. _("Opening G-Code file.")),
  6769. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6770. color=QtGui.QColor("gray"))
  6771. if len(filenames) == 0:
  6772. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6773. else:
  6774. for filename in filenames:
  6775. if filename != '':
  6776. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6777. def on_file_openproject(self, signal):
  6778. """
  6779. File menu callback for opening a project.
  6780. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6781. :return: None
  6782. """
  6783. self.app.log.debug("on_file_openproject()")
  6784. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6785. try:
  6786. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6787. directory=self.app.get_last_folder(), filter=_filter_)
  6788. except TypeError:
  6789. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6790. filename = str(filename)
  6791. if filename == "":
  6792. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6793. else:
  6794. # self.worker_task.emit({'fcn': self.open_project,
  6795. # 'params': [filename]})
  6796. # The above was failing because open_project() is not
  6797. # thread safe. The new_project()
  6798. self.open_project(filename)
  6799. def on_fileopenhpgl2(self, signal, name=None):
  6800. """
  6801. File menu callback for opening a HPGL2.
  6802. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6803. :param name:
  6804. :return: None
  6805. """
  6806. self.app.log.debug("on_fileopenhpgl2()")
  6807. _filter_ = "HPGL2 Files (*.plt);;" \
  6808. "All Files (*.*)"
  6809. if name is None:
  6810. try:
  6811. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6812. directory=self.app.get_last_folder(),
  6813. filter=_filter_)
  6814. except TypeError:
  6815. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6816. filenames = [str(filename) for filename in filenames]
  6817. else:
  6818. filenames = [name]
  6819. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6820. "Canvas initialization finished in"),
  6821. '%.2f' % self.app.used_time,
  6822. _("Opening HPGL2 file.")),
  6823. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6824. color=QtGui.QColor("gray"))
  6825. if len(filenames) == 0:
  6826. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6827. else:
  6828. for filename in filenames:
  6829. if filename != '':
  6830. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6831. def on_file_openconfig(self, signal):
  6832. """
  6833. File menu callback for opening a config file.
  6834. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6835. :return: None
  6836. """
  6837. self.app.log.debug("on_file_openconfig()")
  6838. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6839. try:
  6840. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6841. directory=self.app.data_path, filter=_filter_)
  6842. except TypeError:
  6843. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6844. filter=_filter_)
  6845. if filename == "":
  6846. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6847. else:
  6848. self.open_config_file(filename)
  6849. def on_file_exportsvg(self):
  6850. """
  6851. Callback for menu item File->Export SVG.
  6852. :return: None
  6853. """
  6854. self.app.log.debug("on_file_exportsvg()")
  6855. obj = self.app.collection.get_active()
  6856. if obj is None:
  6857. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6858. msg = _("Please Select a Geometry object to export")
  6859. msgbox = QtWidgets.QMessageBox()
  6860. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6861. msgbox.setInformativeText(msg)
  6862. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6863. msgbox.setDefaultButton(bt_ok)
  6864. msgbox.exec_()
  6865. return
  6866. # Check for more compatible types and add as required
  6867. if (not isinstance(obj, GeometryObject)
  6868. and not isinstance(obj, GerberObject)
  6869. and not isinstance(obj, CNCJobObject)
  6870. and not isinstance(obj, ExcellonObject)):
  6871. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6872. msgbox = QtWidgets.QMessageBox()
  6873. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6874. msgbox.setInformativeText(msg)
  6875. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6876. msgbox.setDefaultButton(bt_ok)
  6877. msgbox.exec_()
  6878. return
  6879. name = obj.options["name"]
  6880. _filter = "SVG File (*.svg);;All Files (*.*)"
  6881. try:
  6882. filename, _f = FCFileSaveDialog.get_saved_filename(
  6883. caption=_("Export SVG"),
  6884. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6885. ext_filter=_filter)
  6886. except TypeError:
  6887. filename, _f = FCFileSaveDialog.get_saved_filename(
  6888. caption=_("Export SVG"),
  6889. ext_filter=_filter)
  6890. filename = str(filename)
  6891. if filename == "":
  6892. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6893. return
  6894. else:
  6895. self.export_svg(name, filename)
  6896. if self.defaults["global_open_style"] is False:
  6897. self.app.file_opened.emit("SVG", filename)
  6898. self.app.file_saved.emit("SVG", filename)
  6899. def on_file_exportpng(self):
  6900. self.app.log.debug("on_file_exportpng()")
  6901. date = str(datetime.today()).rpartition('.')[0]
  6902. date = ''.join(c for c in date if c not in ':-')
  6903. date = date.replace(' ', '_')
  6904. data = None
  6905. if self.app.is_legacy is False:
  6906. image = _screenshot(alpha=False)
  6907. data = np.asarray(image)
  6908. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6909. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6910. return
  6911. filter_ = "PNG File (*.png);;All Files (*.*)"
  6912. try:
  6913. filename, _f = FCFileSaveDialog.get_saved_filename(
  6914. caption=_("Export PNG Image"),
  6915. directory=self.app.get_last_save_folder() + '/png_' + date,
  6916. ext_filter=filter_)
  6917. except TypeError:
  6918. filename, _f = FCFileSaveDialog.get_saved_filename(
  6919. caption=_("Export PNG Image"),
  6920. ext_filter=filter_)
  6921. filename = str(filename)
  6922. if filename == "":
  6923. self.inform.emit(_("Cancelled."))
  6924. return
  6925. else:
  6926. if self.app.is_legacy is False:
  6927. write_png(filename, data)
  6928. else:
  6929. self.app.plotcanvas.figure.savefig(filename)
  6930. if self.defaults["global_open_style"] is False:
  6931. self.app.file_opened.emit("png", filename)
  6932. self.app.file_saved.emit("png", filename)
  6933. def on_file_savegerber(self):
  6934. """
  6935. Callback for menu item in Project context menu.
  6936. :return: None
  6937. """
  6938. self.app.log.debug("on_file_savegerber()")
  6939. obj = self.app.collection.get_active()
  6940. if obj is None:
  6941. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6942. return
  6943. # Check for more compatible types and add as required
  6944. if not isinstance(obj, GerberObject):
  6945. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6946. return
  6947. name = self.app.collection.get_active().options["name"]
  6948. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6949. try:
  6950. filename, _f = FCFileSaveDialog.get_saved_filename(
  6951. caption="Save Gerber source file",
  6952. directory=self.app.get_last_save_folder() + '/' + name,
  6953. ext_filter=_filter)
  6954. except TypeError:
  6955. filename, _f = FCFileSaveDialog.get_saved_filename(
  6956. caption=_("Save Gerber source file"),
  6957. ext_filter=_filter)
  6958. filename = str(filename)
  6959. if filename == "":
  6960. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6961. return
  6962. else:
  6963. self.save_source_file(name, filename)
  6964. if self.defaults["global_open_style"] is False:
  6965. self.app.file_opened.emit("Gerber", filename)
  6966. self.app.file_saved.emit("Gerber", filename)
  6967. def on_file_savescript(self):
  6968. """
  6969. Callback for menu item in Project context menu.
  6970. :return: None
  6971. """
  6972. self.app.log.debug("on_file_savescript()")
  6973. obj = self.app.collection.get_active()
  6974. if obj is None:
  6975. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6976. return
  6977. # Check for more compatible types and add as required
  6978. if not isinstance(obj, ScriptObject):
  6979. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6980. return
  6981. name = self.app.collection.get_active().options["name"]
  6982. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6983. try:
  6984. filename, _f = FCFileSaveDialog.get_saved_filename(
  6985. caption="Save Script source file",
  6986. directory=self.app.get_last_save_folder() + '/' + name,
  6987. ext_filter=_filter)
  6988. except TypeError:
  6989. filename, _f = FCFileSaveDialog.get_saved_filename(
  6990. caption=_("Save Script source file"),
  6991. ext_filter=_filter)
  6992. filename = str(filename)
  6993. if filename == "":
  6994. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6995. return
  6996. else:
  6997. self.save_source_file(name, filename)
  6998. if self.defaults["global_open_style"] is False:
  6999. self.app.file_opened.emit("Script", filename)
  7000. self.app.file_saved.emit("Script", filename)
  7001. def on_file_savedocument(self):
  7002. """
  7003. Callback for menu item in Project context menu.
  7004. :return: None
  7005. """
  7006. self.app.log.debug("on_file_savedocument()")
  7007. obj = self.app.collection.get_active()
  7008. if obj is None:
  7009. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7010. return
  7011. # Check for more compatible types and add as required
  7012. if not isinstance(obj, ScriptObject):
  7013. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  7014. return
  7015. name = self.app.collection.get_active().options["name"]
  7016. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7017. try:
  7018. filename, _f = FCFileSaveDialog.get_saved_filename(
  7019. caption="Save Document source file",
  7020. directory=self.app.get_last_save_folder() + '/' + name,
  7021. ext_filter=_filter)
  7022. except TypeError:
  7023. filename, _f = FCFileSaveDialog.get_saved_filename(
  7024. caption=_("Save Document source file"),
  7025. ext_filter=_filter)
  7026. filename = str(filename)
  7027. if filename == "":
  7028. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7029. return
  7030. else:
  7031. self.save_source_file(name, filename)
  7032. if self.defaults["global_open_style"] is False:
  7033. self.app.file_opened.emit("Document", filename)
  7034. self.app.file_saved.emit("Document", filename)
  7035. def on_file_saveexcellon(self):
  7036. """
  7037. Callback for menu item in project context menu.
  7038. :return: None
  7039. """
  7040. self.app.log.debug("on_file_saveexcellon()")
  7041. obj = self.app.collection.get_active()
  7042. if obj is None:
  7043. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7044. return
  7045. # Check for more compatible types and add as required
  7046. if not isinstance(obj, ExcellonObject):
  7047. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7048. return
  7049. name = self.app.collection.get_active().options["name"]
  7050. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7051. try:
  7052. filename, _f = FCFileSaveDialog.get_saved_filename(
  7053. caption=_("Save Excellon source file"),
  7054. directory=self.app.get_last_save_folder() + '/' + name,
  7055. ext_filter=_filter)
  7056. except TypeError:
  7057. filename, _f = FCFileSaveDialog.get_saved_filename(
  7058. caption=_("Save Excellon source file"), ext_filter=_filter)
  7059. filename = str(filename)
  7060. if filename == "":
  7061. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7062. return
  7063. else:
  7064. self.save_source_file(name, filename)
  7065. if self.defaults["global_open_style"] is False:
  7066. self.app.file_opened.emit("Excellon", filename)
  7067. self.app.file_saved.emit("Excellon", filename)
  7068. def on_file_exportexcellon(self):
  7069. """
  7070. Callback for menu item File->Export->Excellon.
  7071. :return: None
  7072. """
  7073. self.app.log.debug("on_file_exportexcellon()")
  7074. obj = self.app.collection.get_active()
  7075. if obj is None:
  7076. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7077. return
  7078. # Check for more compatible types and add as required
  7079. if not isinstance(obj, ExcellonObject):
  7080. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7081. return
  7082. name = self.app.collection.get_active().options["name"]
  7083. _filter = self.defaults["excellon_save_filters"]
  7084. try:
  7085. filename, _f = FCFileSaveDialog.get_saved_filename(
  7086. caption=_("Export Excellon"),
  7087. directory=self.app.get_last_save_folder() + '/' + name,
  7088. ext_filter=_filter)
  7089. except TypeError:
  7090. filename, _f = FCFileSaveDialog.get_saved_filename(
  7091. caption=_("Export Excellon"),
  7092. ext_filter=_filter)
  7093. filename = str(filename)
  7094. if filename == "":
  7095. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7096. return
  7097. else:
  7098. used_extension = filename.rpartition('.')[2]
  7099. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7100. self.export_excellon(name, filename)
  7101. if self.defaults["global_open_style"] is False:
  7102. self.app.file_opened.emit("Excellon", filename)
  7103. self.app.file_saved.emit("Excellon", filename)
  7104. def on_file_exportgerber(self):
  7105. """
  7106. Callback for menu item File->Export->Gerber.
  7107. :return: None
  7108. """
  7109. App.log.debug("on_file_exportgerber()")
  7110. obj = self.app.collection.get_active()
  7111. if obj is None:
  7112. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7113. return
  7114. # Check for more compatible types and add as required
  7115. if not isinstance(obj, GerberObject):
  7116. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7117. return
  7118. name = self.app.collection.get_active().options["name"]
  7119. _filter_ = self.defaults['gerber_save_filters']
  7120. try:
  7121. filename, _f = FCFileSaveDialog.get_saved_filename(
  7122. caption=_("Export Gerber"),
  7123. directory=self.app.get_last_save_folder() + '/' + name,
  7124. ext_filter=_filter_)
  7125. except TypeError:
  7126. filename, _f = FCFileSaveDialog.get_saved_filename(
  7127. caption=_("Export Gerber"),
  7128. ext_filter=_filter_)
  7129. filename = str(filename)
  7130. if filename == "":
  7131. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7132. return
  7133. else:
  7134. used_extension = filename.rpartition('.')[2]
  7135. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7136. self.export_gerber(name, filename)
  7137. if self.defaults["global_open_style"] is False:
  7138. self.app.file_opened.emit("Gerber", filename)
  7139. self.app.file_saved.emit("Gerber", filename)
  7140. def on_file_exportdxf(self):
  7141. """
  7142. Callback for menu item File->Export DXF.
  7143. :return: None
  7144. """
  7145. App.log.debug("on_file_exportdxf()")
  7146. obj = self.app.collection.get_active()
  7147. if obj is None:
  7148. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7149. msg = _("Please Select a Geometry object to export")
  7150. msgbox = QtWidgets.QMessageBox()
  7151. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7152. msgbox.setInformativeText(msg)
  7153. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7154. msgbox.setDefaultButton(bt_ok)
  7155. msgbox.exec_()
  7156. return
  7157. # Check for more compatible types and add as required
  7158. if not isinstance(obj, GeometryObject):
  7159. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7160. msgbox = QtWidgets.QMessageBox()
  7161. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7162. msgbox.setInformativeText(msg)
  7163. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7164. msgbox.setDefaultButton(bt_ok)
  7165. msgbox.exec_()
  7166. return
  7167. name = self.app.collection.get_active().options["name"]
  7168. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7169. try:
  7170. filename, _f = FCFileSaveDialog.get_saved_filename(
  7171. caption=_("Export DXF"),
  7172. directory=self.app.get_last_save_folder() + '/' + name,
  7173. ext_filter=_filter_)
  7174. except TypeError:
  7175. filename, _f = FCFileSaveDialog.get_saved_filename(
  7176. caption=_("Export DXF"),
  7177. ext_filter=_filter_)
  7178. filename = str(filename)
  7179. if filename == "":
  7180. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7181. return
  7182. else:
  7183. self.export_dxf(name, filename)
  7184. if self.defaults["global_open_style"] is False:
  7185. self.app.file_opened.emit("DXF", filename)
  7186. self.app.file_saved.emit("DXF", filename)
  7187. def on_file_importsvg(self, type_of_obj):
  7188. """
  7189. Callback for menu item File->Import SVG.
  7190. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7191. :type type_of_obj: str
  7192. :return: None
  7193. """
  7194. self.app.log.debug("on_file_importsvg()")
  7195. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7196. try:
  7197. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7198. directory=self.app.get_last_folder(),
  7199. filter=_filter_)
  7200. except TypeError:
  7201. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7202. filter=_filter_)
  7203. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7204. type_of_obj = "geometry"
  7205. filenames = [str(filename) for filename in filenames]
  7206. if len(filenames) == 0:
  7207. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7208. else:
  7209. for filename in filenames:
  7210. if filename != '':
  7211. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7212. def on_file_importdxf(self, type_of_obj):
  7213. """
  7214. Callback for menu item File->Import DXF.
  7215. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7216. :type type_of_obj: str
  7217. :return: None
  7218. """
  7219. self.app.log.debug("on_file_importdxf()")
  7220. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7221. try:
  7222. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7223. directory=self.app.get_last_folder(),
  7224. filter=_filter_)
  7225. except TypeError:
  7226. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7227. filter=_filter_)
  7228. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7229. type_of_obj = "geometry"
  7230. filenames = [str(filename) for filename in filenames]
  7231. if len(filenames) == 0:
  7232. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7233. else:
  7234. for filename in filenames:
  7235. if filename != '':
  7236. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7237. def on_file_new_click(self):
  7238. """
  7239. Callback for menu item File -> New.
  7240. Executed on clicking the Menu -> File -> New Project
  7241. :return:
  7242. """
  7243. if self.app.collection.get_list() and self.app.should_we_save:
  7244. msgbox = QtWidgets.QMessageBox()
  7245. # msgbox.setText("<B>Save changes ...</B>")
  7246. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7247. "Creating a New project will delete them.\n"
  7248. "Do you want to Save the project?"))
  7249. msgbox.setWindowTitle(_("Save changes"))
  7250. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7251. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7252. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7253. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7254. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7255. msgbox.setDefaultButton(bt_yes)
  7256. msgbox.exec_()
  7257. response = msgbox.clickedButton()
  7258. if response == bt_yes:
  7259. self.on_file_saveprojectas()
  7260. elif response == bt_cancel:
  7261. return
  7262. elif response == bt_no:
  7263. self.on_file_new()
  7264. else:
  7265. self.on_file_new()
  7266. self.inform.emit('[success] %s...' % _("New Project created"))
  7267. def on_file_new(self, cli=None):
  7268. """
  7269. Returns the application to its startup state. This method is thread-safe.
  7270. :param cli: Boolean. If True this method was run from command line
  7271. :return: None
  7272. """
  7273. self.defaults.report_usage("on_file_new")
  7274. # Remove everything from memory
  7275. self.app.log.debug("on_file_new()")
  7276. # close any editor that might be open
  7277. if self.app.call_source != 'app':
  7278. self.app.editor2object(cleanup=True)
  7279. # ## EDITOR section
  7280. self.app.geo_editor = AppGeoEditor(self.app)
  7281. self.app.exc_editor = AppExcEditor(self.app)
  7282. self.app.grb_editor = AppGerberEditor(self.app)
  7283. # Clear pool
  7284. self.app.clear_pool()
  7285. for obj in self.app.collection.get_list():
  7286. # delete shapes left drawn from mark shape_collections, if any
  7287. if isinstance(obj, GerberObject):
  7288. try:
  7289. obj.mark_shapes_storage.clear()
  7290. obj.mark_shapes.clear(update=True)
  7291. obj.mark_shapes.enabled = False
  7292. except AttributeError:
  7293. pass
  7294. # also delete annotation shapes, if any
  7295. elif isinstance(obj, CNCJobObject):
  7296. try:
  7297. obj.text_col.enabled = False
  7298. del obj.text_col
  7299. obj.annotation.clear(update=True)
  7300. del obj.annotation
  7301. except AttributeError:
  7302. pass
  7303. # delete the exclusion areas
  7304. self.app.exc_areas.clear_shapes()
  7305. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7306. self.app.shell.init_tcl()
  7307. # delete any selection shape on canvas
  7308. self.app.delete_selection_shape()
  7309. # delete all FlatCAM objects
  7310. self.app.collection.delete_all()
  7311. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7312. self.app.setup_default_properties_tab()
  7313. # Clear project filename
  7314. self.app.project_filename = None
  7315. # Load the application defaults
  7316. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7317. # Re-fresh project options
  7318. self.app.on_options_app2project()
  7319. # Init FlatCAMTools
  7320. self.app.init_tools()
  7321. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7322. if cli is None:
  7323. # we need to go in reverse because once we remove a tab then the index changes
  7324. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7325. # and so on. Therefore the deletion should be done in reverse
  7326. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7327. for index in range(wdg_count, -1, -1):
  7328. try:
  7329. self.app.ui.plot_tab_area.closeTab(index)
  7330. except Exception as e:
  7331. log.debug("App.on_file_new() --> %s" % str(e))
  7332. # # And then add again the Plot Area
  7333. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7334. self.app.ui.plot_tab_area.protectTab(0)
  7335. # take the focus of the Notebook on Project Tab.
  7336. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7337. self.app.ui.set_ui_title(name=_("New Project - Not saved"))
  7338. def on_filenewscript(self, silent=False):
  7339. """
  7340. Will create a new script file and open it in the Code Editor
  7341. :param silent: if True will not display status messages
  7342. :return: None
  7343. """
  7344. if silent is False:
  7345. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7346. # hide coordinates toolbars in the infobar while in DB
  7347. self.app.ui.coords_toolbar.hide()
  7348. self.app.ui.delta_coords_toolbar.hide()
  7349. self.app.app_obj.new_script_object()
  7350. def on_fileopenscript(self, name=None, silent=False):
  7351. """
  7352. Will open a Tcl script file into the Code Editor
  7353. :param silent: if True will not display status messages
  7354. :param name: name of a Tcl script file to open
  7355. :return: None
  7356. """
  7357. self.app.log.debug("on_fileopenscript()")
  7358. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7359. "All Files (*.*)"
  7360. if name:
  7361. filenames = [name]
  7362. else:
  7363. try:
  7364. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7365. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7366. except TypeError:
  7367. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7368. if len(filenames) == 0:
  7369. if silent is False:
  7370. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7371. else:
  7372. for filename in filenames:
  7373. if filename != '':
  7374. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7375. def on_fileopenscript_example(self, name=None, silent=False):
  7376. """
  7377. Will open a Tcl script file into the Code Editor
  7378. :param silent: if True will not display status messages
  7379. :param name: name of a Tcl script file to open
  7380. :return:
  7381. """
  7382. self.app.log.debug("on_fileopenscript_example()")
  7383. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7384. "All Files (*.*)"
  7385. # test if the app was frozen and choose the path for the configuration file
  7386. if getattr(sys, "frozen", False) is True:
  7387. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7388. else:
  7389. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7390. if name:
  7391. filenames = [name]
  7392. else:
  7393. try:
  7394. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7395. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7396. except TypeError:
  7397. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7398. if len(filenames) == 0:
  7399. if silent is False:
  7400. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7401. else:
  7402. for filename in filenames:
  7403. if filename != '':
  7404. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7405. def on_filerunscript(self, name=None, silent=False):
  7406. """
  7407. File menu callback for loading and running a TCL script.
  7408. :param silent: if True will not display status messages
  7409. :param name: name of a Tcl script file to be run by FlatCAM
  7410. :return: None
  7411. """
  7412. self.app.log.debug("on_file_runscript()")
  7413. if name:
  7414. filename = name
  7415. if self.app.cmd_line_headless != 1:
  7416. self.splash.showMessage('%s: %ssec\n%s' %
  7417. (_("Canvas initialization started.\n"
  7418. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7419. _("Executing ScriptObject file.")
  7420. ),
  7421. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7422. color=QtGui.QColor("gray"))
  7423. else:
  7424. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7425. "All Files (*.*)"
  7426. try:
  7427. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7428. directory=self.app.get_last_folder(),
  7429. filter=_filter_)
  7430. except TypeError:
  7431. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7432. # The Qt methods above will return a QString which can cause problems later.
  7433. # So far json.dump() will fail to serialize it.
  7434. filename = str(filename)
  7435. if filename == "":
  7436. if silent is False:
  7437. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7438. else:
  7439. if self.app.cmd_line_headless != 1:
  7440. if self.app.ui.shell_dock.isHidden():
  7441. self.app.ui.shell_dock.show()
  7442. try:
  7443. with open(filename, "r") as tcl_script:
  7444. cmd_line_shellfile_content = tcl_script.read()
  7445. if self.app.cmd_line_headless != 1:
  7446. self.app.shell.exec_command(cmd_line_shellfile_content)
  7447. else:
  7448. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7449. if silent is False:
  7450. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7451. except Exception as e:
  7452. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7453. sys.exit(2)
  7454. def on_file_saveproject(self, silent=False):
  7455. """
  7456. Callback for menu item File->Save Project. Saves the project to
  7457. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7458. if set to None. The project is saved by calling ``self.save_project()``.
  7459. :param silent: if True will not display status messages
  7460. :return: None
  7461. """
  7462. if self.app.project_filename is None:
  7463. self.on_file_saveprojectas()
  7464. else:
  7465. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7466. if self.defaults["global_open_style"] is False:
  7467. self.app.file_opened.emit("project", self.project_filename)
  7468. self.app.file_saved.emit("project", self.project_filename)
  7469. self.app.ui.set_ui_title(name=self.app.project_filename)
  7470. self.app.should_we_save = False
  7471. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7472. """
  7473. Callback for menu item File->Save Project As... Opens a file
  7474. chooser and saves the project to the given file via
  7475. ``self.save_project()``.
  7476. :param make_copy if to be create a copy of the project; boolean
  7477. :param use_thread: if to be run in a separate thread; boolean
  7478. :param quit_action: if to be followed by quiting the application; boolean
  7479. :return: None
  7480. """
  7481. date = str(datetime.today()).rpartition('.')[0]
  7482. date = ''.join(c for c in date if c not in ':-')
  7483. date = date.replace(' ', '_')
  7484. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7485. try:
  7486. filename, _f = FCFileSaveDialog.get_saved_filename(
  7487. caption=_("Save Project As ..."),
  7488. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7489. proj=_("Project")),
  7490. ext_filter=filter_
  7491. )
  7492. except TypeError:
  7493. filename, _f = FCFileSaveDialog.get_saved_filename(
  7494. caption=_("Save Project As ..."),
  7495. ext_filter=filter_)
  7496. filename = str(filename)
  7497. if filename == '':
  7498. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7499. return
  7500. if use_thread is True:
  7501. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7502. else:
  7503. self.save_project(filename, quit_action)
  7504. # self.save_project(filename)
  7505. if self.defaults["global_open_style"] is False:
  7506. self.app.file_opened.emit("project", filename)
  7507. self.app.file_saved.emit("project", filename)
  7508. if not make_copy:
  7509. self.app.project_filename = filename
  7510. self.app.ui.set_ui_title(name=self.app.project_filename)
  7511. self.app.should_we_save = False
  7512. def on_file_save_objects_pdf(self, use_thread=True):
  7513. date = str(datetime.today()).rpartition('.')[0]
  7514. date = ''.join(c for c in date if c not in ':-')
  7515. date = date.replace(' ', '_')
  7516. try:
  7517. obj_selection = self.app.collection.get_selected()
  7518. if len(obj_selection) == 1:
  7519. obj_name = str(obj_selection[0].options['name'])
  7520. else:
  7521. obj_name = _("FlatCAM objects print")
  7522. except AttributeError as err:
  7523. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7524. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7525. return
  7526. if not obj_selection:
  7527. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7528. return
  7529. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7530. try:
  7531. filename, _f = FCFileSaveDialog.get_saved_filename(
  7532. caption=_("Save Object as PDF ..."),
  7533. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7534. obj_name=obj_name,
  7535. date=date),
  7536. ext_filter=filter_
  7537. )
  7538. except TypeError:
  7539. filename, _f = FCFileSaveDialog.get_saved_filename(
  7540. caption=_("Save Object as PDF ..."),
  7541. ext_filter=filter_)
  7542. filename = str(filename)
  7543. if filename == '':
  7544. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7545. return
  7546. if use_thread is True:
  7547. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7548. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7549. else:
  7550. self.save_pdf(filename, obj_selection)
  7551. # self.save_project(filename)
  7552. if self.defaults["global_open_style"] is False:
  7553. self.app.file_opened.emit("pdf", filename)
  7554. self.app.file_saved.emit("pdf", filename)
  7555. def save_pdf(self, file_name, obj_selection):
  7556. p_size = self.defaults['global_workspaceT']
  7557. orientation = self.defaults['global_workspace_orientation']
  7558. color = 'black'
  7559. transparency_level = 1.0
  7560. self.pagesize.update(
  7561. {
  7562. 'Bounds': None,
  7563. 'A0': (841 * mm, 1189 * mm),
  7564. 'A1': (594 * mm, 841 * mm),
  7565. 'A2': (420 * mm, 594 * mm),
  7566. 'A3': (297 * mm, 420 * mm),
  7567. 'A4': (210 * mm, 297 * mm),
  7568. 'A5': (148 * mm, 210 * mm),
  7569. 'A6': (105 * mm, 148 * mm),
  7570. 'A7': (74 * mm, 105 * mm),
  7571. 'A8': (52 * mm, 74 * mm),
  7572. 'A9': (37 * mm, 52 * mm),
  7573. 'A10': (26 * mm, 37 * mm),
  7574. 'B0': (1000 * mm, 1414 * mm),
  7575. 'B1': (707 * mm, 1000 * mm),
  7576. 'B2': (500 * mm, 707 * mm),
  7577. 'B3': (353 * mm, 500 * mm),
  7578. 'B4': (250 * mm, 353 * mm),
  7579. 'B5': (176 * mm, 250 * mm),
  7580. 'B6': (125 * mm, 176 * mm),
  7581. 'B7': (88 * mm, 125 * mm),
  7582. 'B8': (62 * mm, 88 * mm),
  7583. 'B9': (44 * mm, 62 * mm),
  7584. 'B10': (31 * mm, 44 * mm),
  7585. 'C0': (917 * mm, 1297 * mm),
  7586. 'C1': (648 * mm, 917 * mm),
  7587. 'C2': (458 * mm, 648 * mm),
  7588. 'C3': (324 * mm, 458 * mm),
  7589. 'C4': (229 * mm, 324 * mm),
  7590. 'C5': (162 * mm, 229 * mm),
  7591. 'C6': (114 * mm, 162 * mm),
  7592. 'C7': (81 * mm, 114 * mm),
  7593. 'C8': (57 * mm, 81 * mm),
  7594. 'C9': (40 * mm, 57 * mm),
  7595. 'C10': (28 * mm, 40 * mm),
  7596. # American paper sizes
  7597. 'LETTER': (8.5 * inch, 11 * inch),
  7598. 'LEGAL': (8.5 * inch, 14 * inch),
  7599. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7600. # From https://en.wikipedia.org/wiki/Paper_size
  7601. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7602. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7603. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7604. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7605. 'LEDGER': (17 * inch, 11 * inch),
  7606. }
  7607. )
  7608. exported_svg = []
  7609. for obj in obj_selection:
  7610. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7611. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7612. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7613. color = obj.fill_color[:-2]
  7614. transparency_level = obj.fill_color[-2:]
  7615. elif obj.kind.lower() == 'geometry':
  7616. color = self.defaults["global_draw_color"]
  7617. # Change the attributes of the exported SVG
  7618. # We don't need stroke-width
  7619. # We set opacity to maximum
  7620. # We set the colour to WHITE
  7621. root = ET.fromstring(svg_obj)
  7622. for child in root:
  7623. child.set('fill', str(color))
  7624. child.set('opacity', str(transparency_level))
  7625. child.set('stroke', str(color))
  7626. exported_svg.append(ET.tostring(root))
  7627. xmin = Inf
  7628. ymin = Inf
  7629. xmax = -Inf
  7630. ymax = -Inf
  7631. for obj in obj_selection:
  7632. try:
  7633. gxmin, gymin, gxmax, gymax = obj.bounds()
  7634. xmin = min([xmin, gxmin])
  7635. ymin = min([ymin, gymin])
  7636. xmax = max([xmax, gxmax])
  7637. ymax = max([ymax, gymax])
  7638. except Exception as e:
  7639. self.app.log.warning(
  7640. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7641. # Determine bounding area for svg export
  7642. bounds = [xmin, ymin, xmax, ymax]
  7643. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7644. # This contain the measure units
  7645. uom = obj_selection[0].units.lower()
  7646. # Define a boundary around SVG of about 1.0mm (~39mils)
  7647. if uom in "mm":
  7648. boundary = 1.0
  7649. else:
  7650. boundary = 0.0393701
  7651. # Convert everything to strings for use in the xml doc
  7652. svgwidth = str(size[0] + (2 * boundary))
  7653. svgheight = str(size[1] + (2 * boundary))
  7654. minx = str(bounds[0] - boundary)
  7655. miny = str(bounds[1] + boundary + size[1])
  7656. # Add a SVG Header and footer to the svg output from shapely
  7657. # The transform flips the Y Axis so that everything renders
  7658. # properly within svg apps such as inkscape
  7659. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7660. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7661. svg_header += 'width="' + svgwidth + uom + '" '
  7662. svg_header += 'height="' + svgheight + uom + '" '
  7663. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7664. svg_header += '>'
  7665. svg_header += '<g transform="scale(1,-1)">'
  7666. svg_footer = '</g> </svg>'
  7667. svg_elem = str(svg_header)
  7668. for svg_item in exported_svg:
  7669. svg_elem += str(svg_item)
  7670. svg_elem += str(svg_footer)
  7671. # Parse the xml through a xml parser just to add line feeds
  7672. # and to make it look more pretty for the output
  7673. doc = parse_xml_string(svg_elem)
  7674. doc_final = doc.toprettyxml()
  7675. try:
  7676. if self.defaults['units'].upper() == 'IN':
  7677. unit = inch
  7678. else:
  7679. unit = mm
  7680. doc_final = StringIO(doc_final)
  7681. drawing = svg2rlg(doc_final)
  7682. if p_size == 'Bounds':
  7683. renderPDF.drawToFile(drawing, file_name)
  7684. else:
  7685. if orientation == 'p':
  7686. page_size = portrait(self.pagesize[p_size])
  7687. else:
  7688. page_size = landscape(self.pagesize[p_size])
  7689. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7690. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7691. renderPDF.draw(drawing, my_canvas, 0, 0)
  7692. my_canvas.save()
  7693. except Exception as e:
  7694. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7695. return 'fail'
  7696. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7697. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7698. """
  7699. Exports a Geometry Object to an SVG file.
  7700. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7701. :param filename: Path to the SVG file to save to.
  7702. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7703. :return:
  7704. """
  7705. if filename is None:
  7706. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7707. is not None else self.defaults["global_last_folder"]
  7708. self.app.log.debug("export_svg()")
  7709. try:
  7710. obj = self.app.collection.get_by_name(str(obj_name))
  7711. except Exception:
  7712. return 'fail'
  7713. with self.app.proc_container.new(_("Exporting SVG")):
  7714. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7715. # Determine bounding area for svg export
  7716. bounds = obj.bounds()
  7717. size = obj.size()
  7718. # Convert everything to strings for use in the xml doc
  7719. svgwidth = str(size[0])
  7720. svgheight = str(size[1])
  7721. minx = str(bounds[0])
  7722. miny = str(bounds[1] - size[1])
  7723. uom = obj.units.lower()
  7724. # Add a SVG Header and footer to the svg output from shapely
  7725. # The transform flips the Y Axis so that everything renders
  7726. # properly within svg apps such as inkscape
  7727. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7728. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7729. svg_header += 'width="' + svgwidth + uom + '" '
  7730. svg_header += 'height="' + svgheight + uom + '" '
  7731. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7732. svg_header += '<g transform="scale(1,-1)">'
  7733. svg_footer = '</g> </svg>'
  7734. svg_elem = svg_header + exported_svg + svg_footer
  7735. # Parse the xml through a xml parser just to add line feeds
  7736. # and to make it look more pretty for the output
  7737. svgcode = parse_xml_string(svg_elem)
  7738. svgcode = svgcode.toprettyxml()
  7739. try:
  7740. with open(filename, 'w') as fp:
  7741. fp.write(svgcode)
  7742. except PermissionError:
  7743. self.inform.emit('[WARNING] %s' %
  7744. _("Permission denied, saving not possible.\n"
  7745. "Most likely another app is holding the file open and not accessible."))
  7746. return 'fail'
  7747. if self.defaults["global_open_style"] is False:
  7748. self.app.file_opened.emit("SVG", filename)
  7749. self.app.file_saved.emit("SVG", filename)
  7750. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7751. def on_import_preferences(self):
  7752. """
  7753. Loads the application default settings from a saved file into
  7754. ``self.defaults`` dictionary.
  7755. :return: None
  7756. """
  7757. self.app.log.debug("App.on_import_preferences()")
  7758. # Show file chooser
  7759. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7760. try:
  7761. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7762. directory=self.app.data_path,
  7763. filter=filter_)
  7764. except TypeError:
  7765. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7766. filter=filter_)
  7767. filename = str(filename)
  7768. if filename == "":
  7769. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7770. return
  7771. # Load in the defaults from the chosen file
  7772. self.defaults.load(filename=filename, inform=self.inform)
  7773. self.app.preferencesUiManager.on_preferences_edited()
  7774. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7775. def on_export_preferences(self):
  7776. """
  7777. Save the defaults dictionary to a file.
  7778. :return: None
  7779. """
  7780. self.app.log.debug("on_export_preferences()")
  7781. # defaults_file_content = None
  7782. # Show file chooser
  7783. date = str(datetime.today()).rpartition('.')[0]
  7784. date = ''.join(c for c in date if c not in ':-')
  7785. date = date.replace(' ', '_')
  7786. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7787. try:
  7788. filename, _f = FCFileSaveDialog.get_saved_filename(
  7789. caption=_("Export FlatCAM Preferences"),
  7790. directory=self.app.data_path + '/preferences_' + date,
  7791. ext_filter=filter__
  7792. )
  7793. except TypeError:
  7794. filename, _f = FCFileSaveDialog.get_saved_filename(
  7795. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7796. filename = str(filename)
  7797. if filename == "":
  7798. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7799. return 'fail'
  7800. # Update options
  7801. self.app.preferencesUiManager.defaults_read_form()
  7802. self.defaults.propagate_defaults()
  7803. # Save update options
  7804. try:
  7805. self.defaults.write(filename=filename)
  7806. except Exception:
  7807. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7808. return
  7809. if self.defaults["global_open_style"] is False:
  7810. self.app.file_opened.emit("preferences", filename)
  7811. self.app.file_saved.emit("preferences", filename)
  7812. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7813. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7814. """
  7815. Exports a Excellon Object to an Excellon file.
  7816. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7817. :param filename: Path to the Excellon file to save to.
  7818. :param local_use:
  7819. :param use_thread: if to be run in a separate thread
  7820. :return:
  7821. """
  7822. if filename is None:
  7823. if self.defaults["global_last_save_folder"]:
  7824. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7825. else:
  7826. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7827. self.app.log.debug("export_excellon()")
  7828. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7829. self.defaults["excellon_exp_decimals"]
  7830. )
  7831. if local_use is None:
  7832. try:
  7833. obj = self.app.collection.get_by_name(str(obj_name))
  7834. except Exception:
  7835. return "Could not retrieve object: %s" % obj_name
  7836. else:
  7837. obj = local_use
  7838. if not isinstance(obj, ExcellonObject):
  7839. self.inform.emit('[ERROR_NOTCL] %s' %
  7840. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7841. return
  7842. # updated units
  7843. eunits = self.defaults["excellon_exp_units"]
  7844. ewhole = self.defaults["excellon_exp_integer"]
  7845. efract = self.defaults["excellon_exp_decimals"]
  7846. ezeros = self.defaults["excellon_exp_zeros"]
  7847. eformat = self.defaults["excellon_exp_format"]
  7848. slot_type = self.defaults["excellon_exp_slot_type"]
  7849. fc_units = self.defaults['units'].upper()
  7850. if fc_units == 'MM':
  7851. factor = 1 if eunits == 'METRIC' else 0.03937
  7852. else:
  7853. factor = 25.4 if eunits == 'METRIC' else 1
  7854. def make_excellon():
  7855. try:
  7856. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7857. header = 'M48\n'
  7858. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7859. (str(self.app.version), str(self.app.version_date))
  7860. header += ';Filename: %s' % str(obj_name) + '\n'
  7861. header += ';Created on : %s' % time_str + '\n'
  7862. if eformat == 'dec':
  7863. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7864. header += eunits + '\n'
  7865. for tool in obj.tools:
  7866. if eunits == 'METRIC':
  7867. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7868. tool=str(tool),
  7869. dec=2)
  7870. else:
  7871. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7872. tool=str(tool),
  7873. dec=4)
  7874. else:
  7875. if ezeros == 'LZ':
  7876. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7877. form='ndec', e_zeros='LZ', factor=factor,
  7878. slot_type=slot_type)
  7879. header += '%s,%s\n' % (eunits, 'LZ')
  7880. header += format_exc
  7881. for tool in obj.tools:
  7882. if eunits == 'METRIC':
  7883. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7884. float(obj.tools[tool]['tooldia']) * factor,
  7885. tool=str(tool),
  7886. dec=2)
  7887. else:
  7888. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7889. float(obj.tools[tool]['tooldia']) * factor,
  7890. tool=str(tool),
  7891. dec=4)
  7892. else:
  7893. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7894. form='ndec', e_zeros='TZ', factor=factor,
  7895. slot_type=slot_type)
  7896. header += '%s,%s\n' % (eunits, 'TZ')
  7897. header += format_exc
  7898. for tool in obj.tools:
  7899. if eunits == 'METRIC':
  7900. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7901. float(obj.tools[tool]['tooldia']) * factor,
  7902. tool=str(tool),
  7903. dec=2)
  7904. else:
  7905. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7906. float(obj.tools[tool]['tooldia']) * factor,
  7907. tool=str(tool),
  7908. dec=4)
  7909. header += '%\n'
  7910. footer = 'M30\n'
  7911. exported_excellon = header
  7912. exported_excellon += excellon_code
  7913. exported_excellon += footer
  7914. if local_use is None:
  7915. try:
  7916. with open(filename, 'w') as fp:
  7917. fp.write(exported_excellon)
  7918. except PermissionError:
  7919. self.inform.emit('[WARNING] %s' %
  7920. _("Permission denied, saving not possible.\n"
  7921. "Most likely another app is holding the file open and not accessible."))
  7922. return 'fail'
  7923. if self.defaults["global_open_style"] is False:
  7924. self.app.file_opened.emit("Excellon", filename)
  7925. self.app.file_saved.emit("Excellon", filename)
  7926. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7927. else:
  7928. return exported_excellon
  7929. except Exception as e:
  7930. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7931. return 'fail'
  7932. if use_thread is True:
  7933. with self.app.proc_container.new(_("Exporting Excellon")):
  7934. def job_thread_exc(app_obj):
  7935. ret = make_excellon()
  7936. if ret == 'fail':
  7937. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7938. return
  7939. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7940. else:
  7941. eret = make_excellon()
  7942. if eret == 'fail':
  7943. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7944. return 'fail'
  7945. if local_use is not None:
  7946. return eret
  7947. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7948. """
  7949. Exports a Gerber Object to an Gerber file.
  7950. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7951. :param filename: Path to the Gerber file to save to.
  7952. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7953. When not None, the value will be the actual Gerber object for which to create
  7954. the Gerber code
  7955. :param use_thread: if to be run in a separate thread
  7956. :return:
  7957. """
  7958. if filename is None:
  7959. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7960. is not None else self.defaults["global_last_folder"]
  7961. self.app.log.debug("export_gerber()")
  7962. if local_use is None:
  7963. try:
  7964. obj = self.app.collection.get_by_name(str(obj_name))
  7965. except Exception:
  7966. return 'fail'
  7967. else:
  7968. obj = local_use
  7969. # updated units
  7970. gunits = self.defaults["gerber_exp_units"]
  7971. gwhole = self.defaults["gerber_exp_integer"]
  7972. gfract = self.defaults["gerber_exp_decimals"]
  7973. gzeros = self.defaults["gerber_exp_zeros"]
  7974. fc_units = self.defaults['units'].upper()
  7975. if fc_units == 'MM':
  7976. factor = 1 if gunits == 'MM' else 0.03937
  7977. else:
  7978. factor = 25.4 if gunits == 'MM' else 1
  7979. def make_gerber():
  7980. try:
  7981. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7982. header = 'G04*\n'
  7983. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7984. (str(self.app.version), str(self.app.version_date))
  7985. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7986. header += 'G04 Created on : %s*' % time_str + '\n'
  7987. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7988. header += "%MO{units}*%\n".format(units=gunits)
  7989. for apid in obj.apertures:
  7990. if obj.apertures[apid]['type'] == 'C':
  7991. header += "%ADD{apid}{type},{size}*%\n".format(
  7992. apid=str(apid),
  7993. type='C',
  7994. size=(factor * obj.apertures[apid]['size'])
  7995. )
  7996. elif obj.apertures[apid]['type'] == 'R':
  7997. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7998. apid=str(apid),
  7999. type='R',
  8000. width=(factor * obj.apertures[apid]['width']),
  8001. height=(factor * obj.apertures[apid]['height'])
  8002. )
  8003. elif obj.apertures[apid]['type'] == 'O':
  8004. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8005. apid=str(apid),
  8006. type='O',
  8007. width=(factor * obj.apertures[apid]['width']),
  8008. height=(factor * obj.apertures[apid]['height'])
  8009. )
  8010. header += '\n'
  8011. # obsolete units but some software may need it
  8012. if gunits == 'IN':
  8013. header += 'G70*\n'
  8014. else:
  8015. header += 'G71*\n'
  8016. # Absolute Mode
  8017. header += 'G90*\n'
  8018. header += 'G01*\n'
  8019. # positive polarity
  8020. header += '%LPD*%\n'
  8021. footer = 'M02*\n'
  8022. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8023. exported_gerber = header
  8024. exported_gerber += gerber_code
  8025. exported_gerber += footer
  8026. if local_use is None:
  8027. try:
  8028. with open(filename, 'w') as fp:
  8029. fp.write(exported_gerber)
  8030. except PermissionError:
  8031. self.inform.emit('[WARNING] %s' %
  8032. _("Permission denied, saving not possible.\n"
  8033. "Most likely another app is holding the file open and not accessible."))
  8034. return 'fail'
  8035. if self.defaults["global_open_style"] is False:
  8036. self.app.file_opened.emit("Gerber", filename)
  8037. self.app.file_saved.emit("Gerber", filename)
  8038. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8039. else:
  8040. return exported_gerber
  8041. except Exception as e:
  8042. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8043. return 'fail'
  8044. if use_thread is True:
  8045. with self.app.proc_container.new(_("Exporting Gerber")):
  8046. def job_thread_grb(app_obj):
  8047. ret = make_gerber()
  8048. if ret == 'fail':
  8049. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8050. return
  8051. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8052. else:
  8053. gret = make_gerber()
  8054. if gret == 'fail':
  8055. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8056. return 'fail'
  8057. if local_use is not None:
  8058. return gret
  8059. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  8060. """
  8061. Exports a Geometry Object to an DXF file.
  8062. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8063. :param filename: Path to the DXF file to save to.
  8064. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8065. When not None, the value will be the actual Geometry object for which to create
  8066. the Geometry/DXF code
  8067. :param use_thread: if to be run in a separate thread
  8068. :return:
  8069. """
  8070. if filename is None:
  8071. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8072. is not None else self.defaults["global_last_folder"]
  8073. self.app.log.debug("export_dxf()")
  8074. if local_use is None:
  8075. try:
  8076. obj = self.app.collection.get_by_name(str(obj_name))
  8077. except Exception:
  8078. return 'fail'
  8079. else:
  8080. obj = local_use
  8081. def make_dxf():
  8082. try:
  8083. dxf_code = obj.export_dxf()
  8084. if local_use is None:
  8085. try:
  8086. dxf_code.saveas(filename)
  8087. except PermissionError:
  8088. self.inform.emit('[WARNING] %s' %
  8089. _("Permission denied, saving not possible.\n"
  8090. "Most likely another app is holding the file open and not accessible."))
  8091. return 'fail'
  8092. if self.defaults["global_open_style"] is False:
  8093. self.app.file_opened.emit("DXF", filename)
  8094. self.app.file_saved.emit("DXF", filename)
  8095. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8096. else:
  8097. return dxf_code
  8098. except Exception as e:
  8099. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8100. return 'fail'
  8101. if use_thread is True:
  8102. with self.app.proc_container.new(_("Exporting DXF")):
  8103. def job_thread_exc(app_obj):
  8104. ret_dxf_val = make_dxf()
  8105. if ret_dxf_val == 'fail':
  8106. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8107. return
  8108. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8109. else:
  8110. ret = make_dxf()
  8111. if ret == 'fail':
  8112. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8113. return
  8114. if local_use is not None:
  8115. return ret
  8116. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8117. """
  8118. Adds a new Geometry Object to the projects and populates
  8119. it with shapes extracted from the SVG file.
  8120. :param plot: If True then the resulting object will be plotted on canvas
  8121. :param filename: Path to the SVG file.
  8122. :param geo_type: Type of FlatCAM object that will be created from SVG
  8123. :param outname: The name given to the resulting FlatCAM object
  8124. :return:
  8125. """
  8126. self.app.log.debug("App.import_svg()")
  8127. obj_type = ""
  8128. if geo_type is None or geo_type == "geometry":
  8129. obj_type = "geometry"
  8130. elif geo_type == "gerber":
  8131. obj_type = "gerber"
  8132. else:
  8133. self.inform.emit('[ERROR_NOTCL] %s' %
  8134. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8135. return
  8136. units = self.defaults['units'].upper()
  8137. def obj_init(geo_obj, app_obj):
  8138. geo_obj.import_svg(filename, obj_type, units=units)
  8139. geo_obj.multigeo = True
  8140. with open(filename) as f:
  8141. file_content = f.read()
  8142. geo_obj.source_file = file_content
  8143. # appGUI feedback
  8144. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8145. with self.app.proc_container.new(_("Importing SVG")):
  8146. # Object name
  8147. name = outname or filename.split('/')[-1].split('\\')[-1]
  8148. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8149. if ret == 'fail':
  8150. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8151. return 'fail'
  8152. # Register recent file
  8153. self.app.file_opened.emit("svg", filename)
  8154. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8155. """
  8156. Adds a new Geometry Object to the projects and populates
  8157. it with shapes extracted from the DXF file.
  8158. :param filename: Path to the DXF file.
  8159. :param geo_type: Type of FlatCAM object that will be created from DXF
  8160. :param outname: Name for the imported Geometry
  8161. :param plot: If True then the resulting object will be plotted on canvas
  8162. :return:
  8163. """
  8164. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8165. obj_type = ""
  8166. if geo_type is None or geo_type == "geometry":
  8167. obj_type = "geometry"
  8168. elif geo_type == "gerber":
  8169. obj_type = geo_type
  8170. else:
  8171. self.inform.emit('[ERROR_NOTCL] %s' %
  8172. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8173. return
  8174. units = self.defaults['units'].upper()
  8175. def obj_init(geo_obj, app_obj):
  8176. if obj_type == "geometry":
  8177. geo_obj.import_dxf_as_geo(filename, units=units)
  8178. elif obj_type == "gerber":
  8179. geo_obj.import_dxf_as_gerber(filename, units=units)
  8180. else:
  8181. return "fail"
  8182. geo_obj.multigeo = True
  8183. with open(filename) as f:
  8184. file_content = f.read()
  8185. geo_obj.source_file = file_content
  8186. # appGUI feedback
  8187. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8188. with self.app.proc_container.new(_("Importing DXF")):
  8189. # Object name
  8190. name = outname or filename.split('/')[-1].split('\\')[-1]
  8191. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8192. if ret == 'fail':
  8193. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8194. return 'fail'
  8195. # Register recent file
  8196. self.app.file_opened.emit("dxf", filename)
  8197. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8198. """
  8199. Opens a Gerber file, parses it and creates a new object for
  8200. it in the program. Thread-safe.
  8201. :param outname: Name of the resulting object. None causes the
  8202. name to be that of the file. Str.
  8203. :param filename: Gerber file filename
  8204. :type filename: str
  8205. :param plot: boolean, to plot or not the resulting object
  8206. :param from_tcl: True if run from Tcl Shell
  8207. :return: None
  8208. """
  8209. # How the object should be initialized
  8210. def obj_init(gerber_obj, app_obj):
  8211. assert isinstance(gerber_obj, GerberObject), \
  8212. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8213. # Opening the file happens here
  8214. try:
  8215. gerber_obj.parse_file(filename)
  8216. except IOError:
  8217. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8218. return "fail"
  8219. except ParseError as err:
  8220. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8221. app_obj.log.error(str(err))
  8222. return "fail"
  8223. except Exception as e:
  8224. log.debug("App.open_gerber() --> %s" % str(e))
  8225. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8226. msg += traceback.format_exc()
  8227. app_obj.inform.emit(msg)
  8228. return "fail"
  8229. if gerber_obj.is_empty():
  8230. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8231. _("Object is not Gerber file or empty. Aborting object creation."))
  8232. return "fail"
  8233. self.app.log.debug("open_gerber()")
  8234. with self.app.proc_container.new(_("Opening Gerber")):
  8235. # Object name
  8236. name = outname or filename.split('/')[-1].split('\\')[-1]
  8237. # # ## Object creation # ##
  8238. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8239. if ret_val == 'fail':
  8240. if from_tcl:
  8241. filename = self.defaults['global_tcl_path'] + '/' + name
  8242. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8243. if ret_val == 'fail':
  8244. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8245. return 'fail'
  8246. # Register recent file
  8247. self.app.file_opened.emit("gerber", filename)
  8248. # appGUI feedback
  8249. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8250. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8251. """
  8252. Opens an Excellon file, parses it and creates a new object for
  8253. it in the program. Thread-safe.
  8254. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8255. :param filename: Excellon file filename
  8256. :type filename: str
  8257. :param plot: boolean, to plot or not the resulting object
  8258. :param from_tcl: True if run from Tcl Shell
  8259. :return: None
  8260. """
  8261. self.app.log.debug("open_excellon()")
  8262. # How the object should be initialized
  8263. def obj_init(excellon_obj, app_obj):
  8264. try:
  8265. ret = excellon_obj.parse_file(filename=filename)
  8266. if ret == "fail":
  8267. app_obj.log.debug("Excellon parsing failed.")
  8268. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8269. return "fail"
  8270. except IOError:
  8271. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8272. app_obj.log.debug("Could not open Excellon object.")
  8273. return "fail"
  8274. except Exception:
  8275. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8276. msg += traceback.format_exc()
  8277. app_obj.inform.emit(msg)
  8278. return "fail"
  8279. ret = excellon_obj.create_geometry()
  8280. if ret == 'fail':
  8281. app_obj.log.debug("Could not create geometry for Excellon object.")
  8282. return "fail"
  8283. for tool in excellon_obj.tools:
  8284. if excellon_obj.tools[tool]['solid_geometry']:
  8285. return
  8286. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8287. return "fail"
  8288. with self.app.proc_container.new(_("Opening Excellon.")):
  8289. # Object name
  8290. name = outname or filename.split('/')[-1].split('\\')[-1]
  8291. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8292. if ret_val == 'fail':
  8293. if from_tcl:
  8294. filename = self.defaults['global_tcl_path'] + '/' + name
  8295. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8296. if ret_val == 'fail':
  8297. self.inform.emit('[ERROR_NOTCL] %s' %
  8298. _('Open Excellon file failed. Probable not an Excellon file.'))
  8299. return
  8300. # Register recent file
  8301. self.app.file_opened.emit("excellon", filename)
  8302. # appGUI feedback
  8303. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8304. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8305. """
  8306. Opens a G-gcode file, parses it and creates a new object for
  8307. it in the program. Thread-safe.
  8308. :param filename: G-code file filename
  8309. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8310. :param force_parsing:
  8311. :param plot: If True plot the object on canvas
  8312. :param from_tcl: True if run from Tcl Shell
  8313. :return: None
  8314. """
  8315. self.app.log.debug("open_gcode()")
  8316. # How the object should be initialized
  8317. def obj_init(job_obj, app_obj_):
  8318. """
  8319. :param job_obj: the resulting object
  8320. :type app_obj_: App
  8321. """
  8322. assert isinstance(app_obj_, App), \
  8323. "Initializer expected App, got %s" % type(app_obj_)
  8324. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8325. try:
  8326. f = open(filename)
  8327. gcode = f.read()
  8328. f.close()
  8329. except IOError:
  8330. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8331. return "fail"
  8332. job_obj.gcode = gcode
  8333. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8334. if gcode_ret == "fail":
  8335. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8336. return "fail"
  8337. job_obj.create_geometry()
  8338. with self.app.proc_container.new(_("Opening G-Code.")):
  8339. # Object name
  8340. name = outname or filename.split('/')[-1].split('\\')[-1]
  8341. # New object creation and file processing
  8342. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8343. if ret_val == 'fail':
  8344. if from_tcl:
  8345. filename = self.defaults['global_tcl_path'] + '/' + name
  8346. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8347. if ret_val == 'fail':
  8348. self.inform.emit('[ERROR_NOTCL] %s' %
  8349. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8350. "Try to load it from File menu.\n "
  8351. "Attempting to create a FlatCAM CNCJob Object from "
  8352. "G-Code file failed during processing"))
  8353. return "fail"
  8354. # Register recent file
  8355. self.app.file_opened.emit("cncjob", filename)
  8356. # appGUI feedback
  8357. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8358. def open_hpgl2(self, filename, outname=None):
  8359. """
  8360. Opens a HPGL2 file, parses it and creates a new object for
  8361. it in the program. Thread-safe.
  8362. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8363. :param filename: HPGL2 file filename
  8364. :return: None
  8365. """
  8366. filename = filename
  8367. # How the object should be initialized
  8368. def obj_init(geo_obj, app_obj):
  8369. assert isinstance(geo_obj, GeometryObject), \
  8370. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8371. # Opening the file happens here
  8372. obj = HPGL2(self)
  8373. try:
  8374. HPGL2.parse_file(obj, filename)
  8375. except IOError:
  8376. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8377. return "fail"
  8378. except ParseError as err:
  8379. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8380. app_obj.log.error(str(err))
  8381. return "fail"
  8382. except Exception as e:
  8383. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8384. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8385. msg += traceback.format_exc()
  8386. app_obj.inform.emit(msg)
  8387. return "fail"
  8388. geo_obj.multigeo = True
  8389. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8390. geo_obj.tools = deepcopy(obj.tools)
  8391. geo_obj.source_file = deepcopy(obj.source_file)
  8392. del obj
  8393. if not geo_obj.solid_geometry:
  8394. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8395. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8396. return "fail"
  8397. self.app.log.debug("open_hpgl2()")
  8398. with self.app.proc_container.new(_("Opening HPGL2")):
  8399. # Object name
  8400. name = outname or filename.split('/')[-1].split('\\')[-1]
  8401. # # ## Object creation # ##
  8402. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8403. if ret == 'fail':
  8404. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8405. return 'fail'
  8406. # Register recent file
  8407. self.app.file_opened.emit("geometry", filename)
  8408. # appGUI feedback
  8409. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8410. def open_script(self, filename, outname=None, silent=False):
  8411. """
  8412. Opens a Script file, parses it and creates a new object for
  8413. it in the program. Thread-safe.
  8414. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8415. :param filename: Script file filename
  8416. :param silent: If True there will be no messages printed to StatusBar
  8417. :return: None
  8418. """
  8419. def obj_init(script_obj, app_obj):
  8420. assert isinstance(script_obj, ScriptObject), \
  8421. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8422. if silent is False:
  8423. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8424. try:
  8425. script_obj.parse_file(filename)
  8426. except IOError:
  8427. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8428. return "fail"
  8429. except ParseError as err:
  8430. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8431. app_obj.log.error(str(err))
  8432. return "fail"
  8433. except Exception as e:
  8434. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8435. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8436. msg += traceback.format_exc()
  8437. app_obj.inform.emit(msg)
  8438. return "fail"
  8439. self.app.log.debug("open_script()")
  8440. with self.app.proc_container.new(_("Opening TCL Script...")):
  8441. # Object name
  8442. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8443. # Object creation
  8444. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8445. if ret_val == 'fail':
  8446. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8447. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8448. if ret_val == 'fail':
  8449. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8450. return 'fail'
  8451. # Register recent file
  8452. self.app.file_opened.emit("script", filename)
  8453. # appGUI feedback
  8454. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8455. def open_config_file(self, filename, run_from_arg=None):
  8456. """
  8457. Loads a config file from the specified file.
  8458. :param filename: Name of the file from which to load.
  8459. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8460. :return: None
  8461. """
  8462. self.app.log.debug("Opening config file: " + filename)
  8463. if run_from_arg:
  8464. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8465. "Canvas initialization finished in"),
  8466. '%.2f' % self.app.used_time,
  8467. _("Opening FlatCAM Config file.")),
  8468. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8469. color=QtGui.QColor("gray"))
  8470. # # add the tab if it was closed
  8471. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8472. # # first clear previous text in text editor (if any)
  8473. # self.ui.text_editor_tab.code_editor.clear()
  8474. #
  8475. # # Switch plot_area to CNCJob tab
  8476. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8477. # close the Code editor if already open
  8478. if self.app.toggle_codeeditor:
  8479. self.app.on_toggle_code_editor()
  8480. self.app.on_toggle_code_editor()
  8481. try:
  8482. if filename:
  8483. f = QtCore.QFile(filename)
  8484. if f.open(QtCore.QIODevice.ReadOnly):
  8485. stream = QtCore.QTextStream(f)
  8486. code_edited = stream.readAll()
  8487. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8488. f.close()
  8489. except IOError:
  8490. self.app.log.error("Failed to open config file: %s" % filename)
  8491. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8492. return
  8493. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8494. """
  8495. Loads a project from the specified file.
  8496. 1) Loads and parses file
  8497. 2) Registers the file as recently opened.
  8498. 3) Calls on_file_new()
  8499. 4) Updates options
  8500. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8501. 6) Calls plot_all() if plot=True
  8502. :param filename: Name of the file from which to load.
  8503. :param run_from_arg: True if run for arguments
  8504. :param plot: If True plot all objects in the project
  8505. :param cli: Run from command line
  8506. :param from_tcl: True if run from Tcl Sehll
  8507. :return: None
  8508. """
  8509. self.app.log.debug("Opening project: " + filename)
  8510. # block autosaving while a project is loaded
  8511. self.app.block_autosave = True
  8512. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8513. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8514. if cli is None:
  8515. self.app.ui.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8516. if run_from_arg:
  8517. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8518. "Canvas initialization finished in"),
  8519. '%.2f' % self.app.used_time,
  8520. _("Opening FlatCAM Project file.")),
  8521. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8522. color=QtGui.QColor("gray"))
  8523. # Open and parse an uncompressed Project file
  8524. try:
  8525. f = open(filename, 'r')
  8526. except IOError:
  8527. if from_tcl:
  8528. name = filename.split('/')[-1].split('\\')[-1]
  8529. filename = self.defaults['global_tcl_path'] + '/' + name
  8530. try:
  8531. f = open(filename, 'r')
  8532. except IOError:
  8533. self.app.log.error("Failed to open project file: %s" % filename)
  8534. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8535. return
  8536. else:
  8537. self.app.log.error("Failed to open project file: %s" % filename)
  8538. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8539. return
  8540. try:
  8541. d = json.load(f, object_hook=dict2obj)
  8542. except Exception as e:
  8543. self.app.log.error(
  8544. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8545. (filename, str(e)))
  8546. f.close()
  8547. # Open and parse a compressed Project file
  8548. try:
  8549. with lzma.open(filename) as f:
  8550. file_content = f.read().decode('utf-8')
  8551. d = json.loads(file_content, object_hook=dict2obj)
  8552. except Exception as e:
  8553. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8554. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8555. return
  8556. # Clear the current project
  8557. # # NOT THREAD SAFE # ##
  8558. if run_from_arg is True:
  8559. pass
  8560. elif cli is True:
  8561. self.app.delete_selection_shape()
  8562. else:
  8563. self.on_file_new()
  8564. # Project options
  8565. self.app.options.update(d['options'])
  8566. self.app.project_filename = filename
  8567. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8568. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8569. if cli is None:
  8570. self.app.set_screen_units(self.app.options["units"])
  8571. # Re create objects
  8572. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8573. for obj in d['objs']:
  8574. def obj_init(obj_inst, app_inst):
  8575. try:
  8576. obj_inst.from_dict(obj)
  8577. except Exception as erro:
  8578. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8579. return 'fail'
  8580. self.app.log.debug(
  8581. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8582. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8583. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8584. if cli is None:
  8585. self.app.ui.set_ui_title(name="{} {}: {}".format(
  8586. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8587. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8588. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8589. self.app.should_we_save = False
  8590. self.app.file_opened.emit("project", filename)
  8591. # restore autosaving after a project was loaded
  8592. self.app.block_autosave = False
  8593. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8594. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8595. if cli is None:
  8596. self.app.ui.set_ui_title(name=self.app.project_filename)
  8597. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8598. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8599. """
  8600. Saves the current project to the specified file.
  8601. :param filename: Name of the file in which to save.
  8602. :type filename: str
  8603. :param quit_action: if the project saving will be followed by an app quit; boolean
  8604. :param silent: if True will not display status messages
  8605. :param from_tcl True is run from Tcl Shell
  8606. :return: None
  8607. """
  8608. self.app.log.debug("save_project()")
  8609. self.app.save_in_progress = True
  8610. if from_tcl:
  8611. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8612. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8613. # Capture the latest changes
  8614. # Current object
  8615. try:
  8616. current_object = self.app.collection.get_active()
  8617. if current_object:
  8618. current_object.read_form()
  8619. except Exception as e:
  8620. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8621. # Serialize the whole project
  8622. d = {
  8623. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8624. "options": self.app.options,
  8625. "version": self.app.version
  8626. }
  8627. if self.defaults["global_save_compressed"] is True:
  8628. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8629. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8630. # # Write
  8631. f.write(g)
  8632. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8633. else:
  8634. # Open file
  8635. try:
  8636. f = open(filename, 'w')
  8637. except IOError:
  8638. self.app.log.error("Failed to open file for saving: %s", filename)
  8639. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8640. return
  8641. # Write
  8642. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8643. f.close()
  8644. # verification of the saved project
  8645. # Open and parse
  8646. try:
  8647. saved_f = open(filename, 'r')
  8648. except IOError:
  8649. if silent is False:
  8650. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8651. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8652. return
  8653. try:
  8654. saved_d = json.load(saved_f, object_hook=dict2obj)
  8655. except Exception:
  8656. if silent is False:
  8657. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8658. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8659. f.close()
  8660. return
  8661. saved_f.close()
  8662. if silent is False:
  8663. if 'version' in saved_d:
  8664. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8665. else:
  8666. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8667. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8668. tb_settings = QSettings("Open Source", "FlatCAM")
  8669. lock_state = self.app.ui.lock_action.isChecked()
  8670. tb_settings.setValue('toolbar_lock', lock_state)
  8671. # This will write the setting to the platform specific storage.
  8672. del tb_settings
  8673. # if quit:
  8674. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8675. # t.start()
  8676. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8677. def save_source_file(self, obj_name, filename):
  8678. """
  8679. Exports a FlatCAM Object to an Gerber/Excellon file.
  8680. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8681. :param filename: Path to the Gerber file to save to.
  8682. :return:
  8683. """
  8684. if filename is None:
  8685. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8686. is not None else self.defaults["global_last_folder"]
  8687. self.app.log.debug("save source file()")
  8688. obj = self.app.collection.get_by_name(obj_name)
  8689. file_string = StringIO(obj.source_file)
  8690. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8691. if file_string.getvalue() == '':
  8692. self.inform.emit('[ERROR_NOTCL] %s' %
  8693. _("Save cancelled because source file is empty. Try to export the file."))
  8694. return 'fail'
  8695. try:
  8696. with open(filename, 'w') as file:
  8697. file.writelines('G04*\n')
  8698. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8699. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8700. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8701. file.writelines('G04 Created on : %s*\n' % time_string)
  8702. for line in file_string:
  8703. file.writelines(line)
  8704. except PermissionError:
  8705. self.inform.emit('[WARNING] %s' %
  8706. _("Permission denied, saving not possible.\n"
  8707. "Most likely another app is holding the file open and not accessible."))
  8708. return 'fail'
  8709. def on_file_savedefaults(self):
  8710. """
  8711. Callback for menu item File->Save Defaults. Saves application default options
  8712. ``self.defaults`` to current_defaults.FlatConfig.
  8713. :return: None
  8714. """
  8715. self.app.preferencesUiManager.save_defaults()
  8716. # end of file